Note that an exception can be throw across invocations. Let us demonstrate it using an example in listing 6.
Listing 6: | multilevel |
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.