C++中的异常处理
1.C++中的异常处理:abort()函数
错误返回码与abort函数
1.当异常条件非常多时,可能无法枚举所有异常条件,或者遗忘部分异常条件
2.对函数或者方法返回的错误码没有进行判断,可能会造成严重后果
示例代码:
1 #include<iostream>
2 using namespace std;
3
4 int factorial(int n)
5 {
6 if(n<0)
7 {
8 return -1;
9 abort();
10 }
12 if(n == 0)
13 {
14 return 1;
15 }
16 else
17 {
18 return n*factorial(n-1);
19 }
20
21 }
22
23 int main()
24 {
25 //错误返回码与abort函数
26 //1.当异常条件非常多时,可能无法枚举所有异常条件,或者遗忘部分异常条件
27 //2.对函数或者方法返回的错误码没有进行判断,可能会造成严重后果
28 int n = 5;
29 int result = factorial(n);
30 if(result > 0)
31 {
32 cout << "n! = " << result << endl;
33 }
34 else if(result == -1)
35 {
36 cout << "n不能等于0" << endl;
37 }
38 }
2.C++中的异常处理:try…catch函数
引发异常与捕捉异常(throw、try、catch)
1.引发异常throw
2.将可能产生异常的代码用try…catch括起来
3.在catch中处理异常
优点:不需要对返回值进行判断,如果有异常发生,直接通过throw跳到异常处理的程序段
示例代码:
1 #include<iostream>
2 using namespace std;
3
4 int factorial(int n)
5 {
6 if(n < 0)
7 {
8 //return -1;
9 throw "n不能小于0";
10 }
11 if(n == 0)
12 {
13 return 1;
14 }
15 else
16 {
17 return n*factorial(n-1);
18 }
19 }
20
21 void process()
22 {
23 try
24 {
25 int n = -10;
26 int jc = factorial(n);
27 cout << "n! = " << jc << endl;
28 }
29 catch