2. 异常处理的基本语法
下面是一个基本的代码例子,说明 throw、try、catch的基本用法,与 catch的类型自动匹配:
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 int test_1(int num)
7 {
8 if (num != 0)
9 {
10 throw - 1; //抛出一个int类型的异常,如果 30 行传1过来,那么将会抛出该异常至36行的 try
11 }
12 else {
13 throw new string("抛出字符串异常"); //抛出一个字符串异常,如果 30 行传0过来,那么将会抛出该字符串异常,catch将会匹配42行
14 }
15
16 return 0;
17 }
18
19 int test_2(int num) //函数进行了嵌套
20 {
21 test_1(num);
22 return 0;
23 }
24
25 int main()
26 {
27 int ret = 0;
28 try //try中的方法的返回值会被下边的catch捕捉
29 {
30 ret = test_2(1); //传1过去,将会捕获test_1中的throw -1,将会直接跳出至41行。
31 }
32 catch (int error) { //捕捉到的值会传到 error 变量
33 printf("出现异常了!%d\n", error);
34 }
35 catch (string * error)
36 {
37 printf("捕捉到字符串异常:%s", error->c_str()); //如果30行传过去的是0,可以通过抛出的异常来找合适的类型 string
38 delete error;
39 }
40 catch (...) { //如果没有合适的类型将会进入这里的通配,如果没有这行通配你试着传个浮点型过来编译不会过的。
41 printf("catch...\n");
42 }
43
44 return 0;
45 }
这里在说一下抛出被拦截的情况,同样是上边的代码:
如果下方的代码 test_2 中拦截了 test_1 的异常,那么在main函数调用处将无法获得异常,除非在下方代码的 test_2 中再次抛出(如29行)。
1 #include <iostream>
2 #include <string>
3
4 using namespace std;
5
6 int test_1(int num)
7 {
8 if (num != 0)
9 {
10 throw - 1; //抛出一个int类型的异常,返回到 20 行
11 }else{
12 throw new string("抛出字符串异常");
13 }
14
15 return 0;
16 }
17
18 int test_2(int num)
19 {
20 try //如果这里捕获异常,第38行中的 try 将捕获不到test_1的异常
21 {
22 test_1(num);
23 }
24 catch (...) {
25 printf("test_2 异常抛出");
26 throw 0.01;
27 }
28
29 /* throw */
30 //这里如果再 throw ,38行将会再次接收到 test_1 的异常
31
32 return 0;
33 }
34
35 int main()
36 {
37 int ret = 0;
38 try
39 {
40 ret = test_2(1); //传1过去,将会抛出 test_1 中的 throw -1
41 }
42 catch (int error) {
43 printf("出现异常了!%d\n", error);
44 }
45 catch (string * error)
46 {
47 printf("捕捉到字符串异常:%s", error->c_str());
48 delete error;
49 }
50 catch (...) {
51 printf("catch...\n");
52 }
53
54 return 0;
55 }
3.异常处理接口声明
4.异常类型的生命周期
4.1 throw 基本类型:
4.2 throw 字符串类型:
4.3 throw 类类型异常:
5.异常和继承
6.异常处理的基本思想
7.标准库里的异常类
点击查看
原文链接: https://www.cnblogs.com/CooCoChoco/p/12528807.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/194599
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!