Edit

Share via


Exception handling in MSVC

An exception is an error condition, possibly outside the program's control, that prevents the program from continuing along its regular execution path. Certain operations, including object creation, file input/output, and function calls made from other modules, are all potential sources of exceptions, even when your program is running correctly. Robust code anticipates and handles exceptions. To detect logic errors, use assertions rather than exceptions (see Using Assertions).

Kinds of exceptions

The Microsoft C++ compiler (MSVC) supports three kinds of exception handling:

  • C++ exception handling

    For most C++ programs, you should use C++ exception handling. It's type-safe, and ensures that object destructors are invoked during stack unwinding.

  • Structured exception handling

    Windows supplies its own exception mechanism, called structured exception handling (SEH). It's 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. It still supports its older exception handling macros, which are similar to C++ exceptions in form. For advice about mixing MFC macros and C++ exceptions, see Exceptions: Using MFC Macros and C++ Exceptions.

Use an /EH compiler option to specify the exception handling model to use in a C++ project. Standard C++ exception handling (/EHsc) is the default in new C++ projects in Visual Studio.

We don't recommend you mix the exception handling mechanisms. For example, don't use C++ exceptions with structured exception handling. Using C++ exception handling exclusively makes your code more portable, and it allows you to handle exceptions of any type. For more information about the drawbacks of structured exception handling, see Structured Exception Handling.

In this section

See also

C++ Language Reference
x64 exception handling
Exception Handling (C++/CLI and C++/CX)