Unwinding Exceptions (C++)

From RAD Studio
Jump to: navigation, search

Go Up to Standard C++ Exception Handling

When an exception is thrown, the runtime library takes the thrown object, gets the type of the object, and looks upward in the call stack for a handler whose type matches the type of the thrown object. Once a handler is found, the RTL unwinds the stack to the point of the handler, and executes the handler.

In the unwind process, the RTL calls destructors for all local objects in the stack frames between where the exception was thrown and where it is caught. If a destructor causes an exception to be raised during stack unwinding and does not handle it, terminate is called. Destructors are called by default, but you can switch off the default by using the -xd compiler option.

Note: During the unwind process, the RTL does not call destructors for objects that are allocated on the heap rather than the stack. This is why, for example, VCL applications use finally blocks to ensure that VCL objects, which are always allocated on the heap, are properly freed. There is one exception to this rule, which is the use of safe pointers.

Using RAII wrappers to automatically dispose pointers

If you have local variables that are pointers to objects and an exception is thrown, these pointers are not automatically deleted. This is because there is no good way for the compiler to distinguish between a pointer to data that was allocated for this function only and any other pointer. The class that you can use to ensure that objects allocated for local use are destroyed in the event of an exception is unique_ptr. There is a special case in which memory is freed for a pointer allocated in a function:

std::unique_ptr<TMyObject> obj(new TMyObject());

In this example, if the constructor of TMyObject throws an exception, then the pointer to the object allocated for obj will be deleted by the RTL when it unwinds the exception. This is the only time that the compiler automatically deletes a pointer value for you.

Note: unique_ptr is a class template that is similar with auto_ptr, but provides a better solution (auto_ptr is deprecated).

See Also