zoukankan      html  css  js  c++  java
  • c++中try catch的用法

    c++中try catch的用法

    标签: c++exception数据库sqlc
     分类:
     

    在c++中,可以直接抛出异常之后自己进行捕捉处理,如:(这样就可以在任何自己得到不想要的结果的时候进行中断,比如在进行数据库事务操作的时候,如果某一个语句返回SQL_ERROR则直接抛出异常,在catch块中进行事务回滚)

    [html] view plain copy
     
    1. #include <iostream>  
    2. #include <exception>      // c++标准库异常类---详情见下一篇!
    3. using namespace std;  
    4. int main () {  
    5.     try  
    6.     {  
    7.         throw 1;  
    8.         throw "error";  
    9.     }  
    10.     catch(char *str)  
    11.     {  
    12.         cout <str <endl;  
    13.     }  
    14.     catch(int i)  
    15.     {  
    16.         cout <<endl;  
    17.     }  
    18. }  


    也可以自己定义异常类来进行处理:

    [html] view plain copy
     
    1. #include <iostream>  
    2. #include <exception>  
    3. using namespace std;  
    4.   
    5. //可以自己定义Exception  
    6. class myexception: public exception  
    7. {  
    8.     virtual const char* what() const throw()  
    9.     {  
    10.         return "My exception happened";  
    11.     }  
    12. }myex;  
    13.   
    14. int main () {  
    15.     try  
    16.     {      
    17.         if(true)    //如果,则抛出异常;  
    18.             throw myex;  
    19.     }  
    20.     catch (exception& e)  
    21.     {  
    22.         cout <e.what() <endl;  
    23.     }  
    24.     return 0;  
    25. }  


     同时也可以使用标准异常类进行处理:

    [html] view plain copy
     
    1. #include <iostream>  
    2. #include <exception>  
    3. using namespace std;  
    4.   
    5. int main () {  
    6.     try  
    7.     {  
    8.         int* myarray= new int[100000];  
    9.     }  
    10.     catch (exception& e)  
    11.     {  
    12.         cout << "Standard exception: " <e.what() <endl;  
    13.     }  
    14.     return 0;  
    15. }  
     
    from:http://blog.csdn.net/gukesdo/article/details/6901991
  • 相关阅读:
    Typescript 最佳实践
    《三》大话 Typescript 接口
    二. 细说小程序登陆
    一. 优化小程序自身的Storage
    开始你的第一个npm脚本工具
    javascript 玩转Date对象
    createjs 小游戏开发实战
    前端实现连连看小游戏(1)
    一篇文章带你快速入门createjs
    从0到1完成小程序开发(4)
  • 原文地址:https://www.cnblogs.com/the-tops/p/5590558.html
Copyright © 2011-2022 走看看