Structured Exception Handling
Note Structured exception handling works with C and C++ source files. However, it is not specifically designed for C++. Although destructors for local objects will be called if you use structured exception handling in a C++ program (if you use the /GX compiler option), you can ensure that your code is more portable by using C++ exception handling. The C++ exception handling mechanism is more flexible, in that it can handle exceptions of any type.
There are two structured exception handling mechanisms:
- Exception handlers, which can respond to or dismiss the exception
- Termination handlers, which are called when an exception causes termination inside a block of code
These two types of handlers are distinct, yet they are closely related through a process called "unwinding the stack." When an exception occurs, Windows looks 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.
If you have C modules that use structured exception handling, they can be mixed with C++ modules that use C++ exception handling. See Exception Handling Differences.
END Microsoft Specific
What do you want to know more about?
- Writing an exception handler.
- Writing a termination handler.
- Using structured exception handling with C++.