C++中的異常類只能捕獲普通異常,無法捕獲記憶體異常,除數為零等錯誤。
而後期語言,如java、C#能捕獲所有錯誤,包括記憶體異常等。
以下為C++的簡單異常處理類:
通過繼承實現異常處理
1、定義異常基類
2、定義具體異常類,繼承基類
3、給具體異常類異常資訊賦值
1 /*通過繼承實現異常處理 2 1、定義異常基類 3 2、定義具體異常類,繼承基類 4 3、給具體異常類異常資訊賦值 5 */ 6 class Exception 7 { 8 public: 9 Exception()10 {11 }12 string ErrorMsg;13 string ErrorCode;14 };15 16 class Exception1:public Exception17 {18 public:19 Exception1()20 {21 this->ErrorMsg = "Msg1";22 this->ErrorCode = 1;23 }24 };25 26 class Exception2:public Exception27 {28 public:29 Exception2()30 {31 this->ErrorMsg = "Msg2";32 this->ErrorCode = 2;33 }34 };35 36 void test_exception()37 {38 int i = 0;39 //throw Exception1();40 throw Exception2();41 /*42 throw new Exception1();43 throw new Exception2();44 */45 return;46 }47 48 int main()49 {50 try51 {52 test_exception();53 }/*54 catch(Exception* ex)55 {56 cout<<ex->ErrorMsg<<endl;57 }*/58 59 catch(Exception ex)60 {61 cout<<ex.ErrorMsg<<endl;62 }63 }