1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <iostream>
using namespace std;
void Last() // called by Third()
{
cout << "Start Last" << endl;
cout << "Last throwing int exception" << endl;
throw -1;
cout << "End Last" << endl;
}
void Third() // called by Second()
{
cout << "Start Third" << endl;
Last();
cout << "End Third" << endl;
}
void Second() // called by First()
{
cout << "Start Second" << endl;
try
{
Third();
}
catch(double)
{
cerr << "Second caught double exception" << endl;
}
cout << "End Second" << endl;
}
void First() // called by main()
{
cout << "Start First" << endl;
try
{
Second();
}
catch (int)
{
cerr << "First caught int exception" << endl;
}
catch (double)
{
cerr << "First caught double exception" << endl;
}
cout << "End First" << endl;
}
int main()
{
cout << "Start main" << endl;
try
{
First();
}
catch (int)
{
cerr << "main caught int exception" << endl;
}
cout << "End main" << endl;
return 0;
让我们研究一下这种情况下会发生什么事情。所有启动报表打印是简单的,不需要进一步的解释。last()打印“最后的投掷int例外”,然后把一个int例外。这就是事情开始变得有趣了。
因为last()不处理异常本身,堆栈开始解开。last()立即终止与控制返回给调用者,这是third()。
third()不处理任何例外,所以它立即终止,控制返回到second()。
second()试了试块,并呼吁third()在它,所以程序试图异常与适当的catch块匹配。然而,有没有人在这里int类型的例外,所以second()立即终止,控制返回到first()。
first()也一试块,并呼吁second()在它,所以程序看上去是否有一个int的异常捕捉处理程序。有!因此,first()异常处理,并打印“第一次引起国际例外”。
因为异常已被处理,控制正常继续在CATCH块内first()结束。这意味着first()印”结束第一”,然后正常终止。
控制返回到main()。虽然main()为int异常处理异常,我们已处理的first(),所以在main() catch块不被执行的。main()只打印“主要”然后正常终止。
有很多有趣的原理说明了这个程序: