c++异常

 1 /*
 2 #include <iostream>
 3 using namespace std;
 4 float Div(int a, int b)
 5 {
 6   if (b==0)
 7   {
 8     throw b;//抛出异常
 9   }
10   return a*1.0 / b;
11 }
12 int main()
13 {
14   int a = 10;
15   int b = 0;
16   float result = 0.0f;
17   try
18   {
19     result = Div(a, b);
20   }
21   / *catch (int)//捕获返回值为int类型的异常异常
22   {
23     cout << "b=="<<b << endl;
24   }* /
25   catch (...)//catch all
26   {
27     cout << "b==" << b << endl;
28   }
29   cout << "result=" << result << endl;
30   return 0;
31 }*/
32 
33 
34 
35 /*
36 #include <iostream>
37 #include <cstring>
38 using namespace std;
39 class Error // 异常类Error
40 {
41 public:
42   int errCode; // 异常代码
43   char errMsg[40]; // 异常信息
44   Error(int code, char *msg) // 构造函数
45   {
46     errCode = code; 
47     strcpy(errMsg, msg);
48   }
49   void ShowError() // 显示异常的详细信息
50   {
51     cout << errCode << ": " << errMsg << endl;
52   }
53 };
54 int Div(int n) // 求100 ÷ n
55 {
56   if (n <= 0) // 检查异常:如果n<=0,则属于异常情况
57   {
58     Error err(-1, "输入人数时必须为正整数"); // 定义异常类Error的对象err
59     throw (err); // 抛出异常对象err,然后退出当前函数的执行
60   }
61   // 如果没有异常,则执行如下的正常处理流程
62   return (100 / n);
63 }
64 int main()
65 {
66   int N; // 定义变量N,保存键盘输入的人数
67   cin >> N;
68   try
69   {
70     int result = Div(N); // 调用函数Div进行除法运算
71     cout << "100÷" << N << "=" << result << endl; // 显示100 ÷ N的结果
72   }
73   catch (Error e) // 捕捉Error类的异常,并定义参数e来接收异常对象
74   {
75     e.ShowError(); // 向用户显示所捕捉到异常对象e的详细信息
76   }
77   return 0;
78 }*/

 

posted @ 2020-11-22 09:38  丁帅帅dss  阅读(71)  评论(0)    收藏  举报