c++ try catch

来源:互联网 发布:讨鬼传捏脸详细数据 编辑:程序博客网 时间:2024/06/04 18:57

 

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

[html] view plaincopyprint?
  1. #include <iostream> 
  2. #include <exception> 
  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 <<i <<endl
  17.     } 


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

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


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

[html] view plaincopyprint?
  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; 

 

0 0
原创粉丝点击