Termination handling guarantees that a code body called the Termination Handler will be executed no matter how the guarded body was exited. It doesn't matter whether your function executed cleanly or encountered an exception which was handled by another exception handler, the termination handler will always be executed.
Termination handlers are ideal for simplifying error handling by moving all cleanup code into a common place. This improves program readability.
The basics of a termination handler are
/*Code before try block */ (1)
__try{
/* Guarded body */ (2)
}
__finally{
/*Termination handler */ (3)
}
/*Code after the termination handler */ (4)
The operating system and the compiler work together to guarantee that the __finally block of code will be executed. This is the case even if you were to place a return, goto, break, continue, or a longjump in the guarded body. The execution is always guaranteed to be ordered as the numbered section above. One good use of a termination handler is to free up precious resources such as memory, closing file handles, and releasing semaphores.
![]()
longjmp - Restore Stack
Environment
Structured Exception Handling
Termination Handler - Local Unwind
Termination Handler - Leave and
AbnormalTermination
