Exception Handlers and Termination Handlers

OverviewHow Do IFAQ

The previous section used the term “exception handlers” in a generic sense, but there are actually two kinds:

These two types of handlers are distinct, yet they are closely related through a process called “unwinding the stack.” When an exception occurs, Windows 95 and Windows NT look for the most recently installed exception handler that is currently active. The handler can do one of three things:

  • Pass control to other handlers (fail to recognize the exception).

  • Recognize but dismiss the exception.

  • Recognize and handle the exception.

The exception handler that recognizes the exception may not be in the function that was running when the exception occurred. In some cases it may be in a function much higher on the stack. The currently running function, as well as all functions on the stack frame, are terminated. During this process, the stack is “unwound”: local variables of terminated functions, unless they are static, are cleared from the stack.

As it unwinds the stack, the operating system calls any termination handlers you’ve written for each function. Use of a termination handler gives you a chance to clean up resources that otherwise would remain open due to abnormal termination. If you’ve entered a critical section, you can exit in the termination handler. If the program is going to shut down, you can perform other housekeeping tasks such as closing and removing temporary files.