第64课 C++中的异常处理(上)

C++异常:

示例程序:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 double divide(double a, double b)
 7 {
 8     const double delta = 0.000000000000001;
 9     double ret = 0;
10     
11     if( !((-delta < b) && (b < delta)) )
12     {
13         ret = a / b;
14     }
15     else
16     {
17         throw 0;
18     }
19     
20     return ret;
21 }
22 
23 int main(int argc, char *argv[])
24 {    
25     try
26     {
27         double r = divide(1, 0);
28             
29         cout << "r = " << r << endl;
30     }
31     catch(...)
32     {
33         cout << "Divided by zero..." << endl;
34     }
35     
36     return 0;
37 }

运行结果如下:

 

 异常类型匹配实验:

 1 #include <iostream>
 2 #include <string>
 3 
 4 using namespace std;
 5 
 6 void Demo1()
 7 {
 8     try
 9     {   
10         throw 'c';
11     }
12     catch(char c)
13     {
14         cout << "catch(char c)" << endl;
15     }
16     catch(short c)
17     {
18         cout << "catch(short c)" << endl;
19     }
20     catch(double c)
21     {
22         cout << "catch(double c)" << endl;
23     }
24     catch(...)
25     {
26         cout << "catch(...)" << endl;
27     }
28 }
29 
30 void Demo2()
31 {
32     throw string("D.T.Software");
33 }
34 
35 int main(int argc, char *argv[])
36 {    
37     Demo1();
38     
39     try
40     {
41         Demo2();
42     }
43     catch(char* s)
44     {
45         cout << "catch(char *s)" << endl;
46     }
47     catch(const char* cs)
48     {
49         cout << "catch(const char *cs)" << endl;
50     }
51     catch(string ss)
52     {
53         cout << "catch(string ss)" << endl;
54     }
55     
56     return 0;
57 }

运行结果如下:

小结:

原文地址:https://www.cnblogs.com/wanmeishenghuo/p/9595001.html