Dela via


Exception Handling in Visual C++

Robust code anticipates and handles exceptions. Exceptions occur when a program executes abnormally because of conditions outside the program's control. Certain operations, including object creation and file input/output, are subject to failures that go beyond errors. Out-of-memory conditions, for example, can occur even when your program is running correctly.

Abnormal situations should be handled by throwing and catching exceptions. Such situations are not the same as normal error conditions, such as a function executing correctly, but returning a result code indicating an error. A normal error condition, for example, would be a file status function indicating that a file does not exist. For normal error conditions, the program should examine the error code and respond appropriately.

Abnormal situations are also not the same as erroneous execution, in which, for example, the caller makes a mistake in passing arguments to a function or calls it in an inappropriate context. For erroneous execution, test your inputs and other assumptions with an assertion (see Using Assertions).

Visual C++ supports three kinds of exception handling:

  • C++ exception handling

    Although structured exception handling works with C and C++ source files, it is not specifically designed for C++. For C++ programs, you should use C++ exception handling.

  • Structured exception handling

    Windows supplies its own exception mechanism, called SEH. It is not recommended for C++ or MFC programming. Use SEH only in non-MFC C programs.

  • MFC exceptions

    Since version 3.0, MFC has used C++ exceptions but still supports its older exception handling macros, which are similar to C++ exceptions in form. The older MFC exception handling macros have been supported since version 1.0. Although these macros are not recommended for new programming, they are still supported for backward compatibility. In programs that already use the macros, you can freely use C++ exceptions as well. During preprocessing, the macros evaluate to the exception handling keywords defined in the Visual C++ implementation of the C++ language as of Visual C++ version 2.0. You can leave existing exception macros in place while you begin to use C++ exceptions.

Do not mix the error handling mechanisms; for example, do not use C++ exceptions with SEH. For advice about mixing MFC macros and C++ exceptions, see Exceptions: Using MFC Macros and C++ Exceptions.

For information on handling exceptions in CLR applications, see Exception Handling under /clr.

For information about exception handling on x64 processors, see Exception Handling (x64).

See Also

Other Resources

C++ Language Reference