C++ try catch 捕获空指针异常,数组越界异常

[cpp] view plain copy

  1. #include <exception>  
  2. #include <iostream>  
  3. using namespace std;  
  4.   
  5. /********************************** 
  6. //project -> Properties -> C/C++ -> Code Generation --> Enable C++ Exceptions 
  7. //选择  Yes with SEH Exceptions (/EHa)  这样的话C++的try catch 也可以捕获到空指针,内存越界,0除异常 
  8. //默认是选择Yes (/EHsc) 
  9. **********************************/  
  10.   
  11. void TestIntType()  
  12. {  
  13.     try  
  14.     {  
  15.         throw 1;  
  16.     }  
  17.     catch(...)  
  18.     {  
  19.         cout<< "在 try block 中, 准备抛出一个异常." << endl;  
  20.     }  
  21. }  
  22.   
  23. void TestDoubleType()  
  24. {  
  25.     try  
  26.     {  
  27.         throw 0.5;  
  28.     }  
  29.     catch(...)  
  30.     {  
  31.         cout<< "在 try block 中, 准备抛出一个异常." << endl;  
  32.     }  
  33. }  
  34.   
  35. void TestEmptyPointType()  
  36. {  
  37.     try  
  38.     {  
  39.         int* p = NULL;  
  40.         *p = 3;  
  41.     }  
  42.     catch(...)  
  43.     {  
  44.         cout<< "非法地址操作异常" << endl;  
  45.     }  
  46. }  
  47.   
  48. void TestDivZeroType()  
  49. {  
  50.     try  
  51.     {  
  52.         int b = 0;  
  53.         int a = 3/b;  
  54.     }  
  55.     catch(...)  
  56.     {  
  57.         cout<< "0除异常" << endl;  
  58.     }  
  59. }  
  60.   
  61. void TestMemoryOutType()  
  62. {  
  63.     int * a = new int[4];  
  64.     try  
  65.     {  
  66.         for (int i = 0; i<245; i++)  
  67.         {  
  68.             a++;  
  69.         }  
  70.         *a = 3;  
  71.     }  
  72.     catch(...)  
  73.     {  
  74.         cout<< "内存越界异常" << endl;  
  75.     }  
  76. }  
  77.   
  78. int main(int argc, char* argv[])  
  79. {  
  80.     TestEmptyPointType();  
  81.     //TestDivZeroType();  
  82.     TestMemoryOutType();  
  83.     return 1;  
  84. }  

猜你喜欢

转载自blog.csdn.net/i_likechard/article/details/78042503
今日推荐