When an exception is thrown but not caught in a particular scope, the function-call stack is “unwound,” and an attempt is made to catch
the exception in the next outer try
…catch
block. Unwinding the function call stack means that the function in which the exception was not caught terminates, all local variables that have completed initialization in that function are destroyed and control returns to the statement that originally invoked that function. If a try
block encloses that statement, an attempt is made to catch
the exception. If a try
block does not enclose that statement, stack unwinding occurs again. If no catch
handler ever catches this exception, the program terminates. The program of Fig. 17.4 demonstrates stack unwinding.
In main
, the try
block (lines 30–33) calls function1
(lines 22–25). Next, function1
calls function2
(lines 16–19), which in turn calls function3
(lines 8–13). Line 12 of function3
throws a runtime_error
object. However, because no try
block encloses the throw
statement in line 12, stack unwinding occurs—function3
terminates at line 12, then returns control to the statement in function2
that invoked function3
(i.e., line 18). Because no try
block encloses line 18, stack unwinding occurs again—function2
terminates at line 18 and returns control to the statement in function1
that invoked function2
(i.e., line 24). Because no try
block encloses line 24, stack unwinding occurs one more time—function1
terminates at line 24 and returns control to the statement in main
that invoked function1
(i.e., line 32). The try
block of lines 30–33 encloses this statement, so the first matching catch
handler located after this try
block (line 34–37) catches and processes the exception. Line 35 uses function what
to display the exception message.