C++异常Exception

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 Exception
17 {
18 public:
19     Exception1()
20     {
21         this->ErrorMsg = "Msg1";
22         this->ErrorCode = 1;
23     }
24 };
25 
26 class Exception2:public Exception
27 {
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     try
51     {
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 }
原文地址:https://www.cnblogs.com/jiese/p/2588849.html