Exception Handling Topics (C++)

OverviewHow Do IFAQ

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.

****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 95 and Windows NT. 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 ISO WG21/ANSI X3J16 working papers towards the evolving standard for C++.

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, open the Project Settings dialog box, select the C/C++ tab, select C++ Language in the Category box, and select Enable Exception Handling; or use the /GX compiler option. The default is /GX-, which disables exception handling unwind semantics.

****Note   ****As of version 4.0, the Microsoft Foundation Class Library (MFC), which is included with Visual C++, 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: Macros and C++ Exceptions, and Exceptions: Converting from MFC Exception Macros.

What do you want to know more about?