C++ Exception Handling
The C++ language provides built-in support for handling anomalous situations, known as "exceptions," which may occur during the execution of your program. With C++ exception handling, your program can communicate unexpected events to a higher execution context that is better able to recover from such abnormal events. These exceptions are handled by code that is outside the normal flow of control.
This discussion on C++ exception handling includes:
- The try, catch, and throw Statements
- Exception Specifications
- Function-try Blocks
- Exception Handling: Default Synchronous Exception Model
- Type-Safe Exception Handling
- C++ Exception Examples
- Catchable Types
- Unhandled C++ Exceptions
- Order of Handlers
- Mixing C and C++ exceptions
- Exception Handling Overhead
Note In these articles, the terms "structured exception handling" and "structured exception" (or "C exception") refer exclusively to the Win32 structured exception handling mechanism provided by Windows. All other references to exception handling (or "C++ exception") refer to the C++ exception handling mechanism.
Note MFC now uses C++ exception handling. The older MFC exception macros, if you still use them, evaluate to C++ exception keywords. See Exceptions: Changes to Exception Macros in Version 3.0.
Unlike the Win32 structured exception handling mechanism, the language itself provides support for C++ exception handling. These articles describe the Microsoft implementation of C++ exception handling, which is based on the ANSI C++ Standard.
For C++ programs, you should use C++ exception handling rather than structured exception handling. While structured exception handling works in C++ programs, 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. C exceptions are always of type unsigned int.
Using C++ Exceptions
In C++, the process of raising an exception is called "throwing" an exception. A designated exception handler then "catches" the thrown exception.
To enable C++ exception handling in your code, use /GX.
Note As of version 4.0, MFC uses the C++ exception handling mechanism. Although you are encouraged to use C++ exception handling in new code, MFC version 4.0 and later retains the macros from previous versions of MFC so that old code will not be broken. The macros and the new mechanism can be combined as well. For information on mixing macros and C++ exception handling and on converting old code to use the new mechanism, see the articles Exceptions: Using MFC Macros and C++ Exceptions and Exceptions: Converting from MFC Exception Macros.