4 Magical throwing

Note that an exception can be throw across invocations. Let us demonstrate it using an example in listing 6.


Listing 6:multilevel
 
1class A 
2{ 
3  // make this a complicated class 
4}
5 
6 
7class Exception 
8{ 
9}
10 
11void sub1(void
12{ 
13  try 
14  { 
15    sub2(); 
16    // some more stuff to do here 
17    // will be skipped if exception is thrown 
18  } 
19  catch (Exception e) 
20  { 
21    // what to do when an exception is caught?  
22  } 
23} 
24 
25void sub2(void
26{ 
27  A sub2A; 
28 
29  sub3(); 
30  // some more stuff to do here 
31  // will be skipped if exception is thrown 
32} 
33 
34void sub3(void
35{ 
36  A sub3A; 
37 
38  sub4(); 
39  // some more stuff to do here 
40  // will be skipped if exception is thrown 
41} 
42 
43void sub4(voidthrow Exception 
44{ 
45  throw Exception(); 
46}

When sub4 throw the exception, execution “continues” on line 21. In other words, execution does not return to sub3 or sub2. This can potentially be a problem, but the objects sub3A and sub2A are constructed in sub3 and sub2, respectively. Skipping these two functions means that the objects may not be destroyed correctly.

The throw mechanism unwinds items on the stack step-by-step. As a result, it dealllocates all auto objects on the stack properly, and calls destructor methods when it is appropriate. As a result, even though control is not resumed in sub3 or sub2, the auto objects are deallocated properly with destructor methods called.