(1)try语句块内抛出的异常将被catch的参数(形参)捕获,然后在catch语句块内处理此捕获的异常。

(2)当执行一个throw时,跟在throw后面的语句将不再被执行,程序的控制权由此转移到与之匹配的catch语句块。

(3)为了一次性捕获所有异常,可以使用省略号作为异常声明,即catch(...)。此语句可以与任意类型的异常匹配。

 

1 #include <iostream>
2
3 using namespace std;
4
5 void fun()
6 {
7 for (int i = 0; i < 10; ++i)
8 {
9 if (i == 6)
10 throw i;
11 }
12 }
13
14 int main()
15 {
16 try
17 {
18 fun();
19 }
20
21 catch (int a) //此处的形参a捕获了抛出的i,将i作为了实参,所以此处输出i的值
22 {
23 cout << a << endl;
24 }
25
26 return 0;
27 }

 

1 #include <iostream>
2 #include <string>
3 using namespace std;
4
5 void fun()
6 {
7 for (int i = 0; i < 10; ++i)
8 {
9 if (i == 6)
10 throw "hello"; //此处的"hello"是字面值常量,为const char*类型,而不是string类型,所以将被s2捕获
11 } //若要被string s1捕获,则需要在抛出的时候强制类型转换,即throw string("hello").
12 }
13
14 int main()
15 {
16 try
17 {
18 fun();
19 }
20 catch (string s1) //若要被string s1捕获,则需要在抛出的时候强制类型转换,即throw string("hello").
21 {
22 cout << "string" << endl;
23 }
24
25 catch (const char* s2)
26 {
27 cout << "const char*" << endl;
28 }
29
30
31
32 return 0;
33 }

 

1 #include <iostream>
2
3 using namespace std;
4
5 void fun()
6 {
7 for (int i = 0; i < 10; ++i)
8 {
9 if (i == 6)
10 throw 'c';
11 }
12 }
13
14 int main()
15 {
16 try
17 {
18 fun();
19 }
20
21
22 catch (int a)
23 {
24 cout << a << endl;
25 }
26
27 catch (...) //由于没有与char类型匹配的cath语句,所以此处匹配此任意类型的catch语句
28 {
29 cout << "..." << endl;
30 }

 

注意: 如果catch(...)与其他几个catch语句一起出现,则catch(...)必须在最后的位置。出现在捕获所有异常语句后面的catch语句将永远不会被匹配。