Stack Unwinding

In the last issue we talked about throwing exceptions. Before discussing how exceptions are handled, we need to talk about an intermediate step, stack unwinding.

The exception handling mechanism is dynamic in that a record is kept of the flow of program execution, for example via stack frames and program counter mapping tables. When an exception is thrown, control transfers to the nearest suitable handler. “nearest” in this sense means the nearest dynamically surrounding try block containing a handler that matches the type of the thrown

exception. We will talk more about exception handlers in a future issue. Transfer of control from the point at which an exception is thrown to the exception handler implies jumping out of one program context into another. What about cleanup of the old program context? For example, what about local class objects that have been allocated? Are their destructors called?

The answer is “yes”. All stack-allocated (“automatic”) objects allocated since the try block was entered will have their destructors invoked. Let’s look at an example:

Output of this program is:

In this example, we enter the try block in main(), allocate a3, then call f(). f() allocates a1, then throws an exception, which will transfer control to the catch clause in main().

In this example, the a1 and a3 objects have their destructors called. a2 and a4 do not, because they were never allocated.

It’s possible to have class objects containing other class objects, or arrays of class objects, with partial construction taking place followed by an exception being thrown. In this case, only the constructed subobjects will be destructed.