Mixing C (structured) and C++ exceptions

If you want to write portable code, the use of structured exception handling (SEH) in a C++ program isn't recommended. However, you may sometimes want to compile using /EHa and mix structured exceptions and C++ source code, and need some facility for handling both kinds of exceptions. Because a structured exception handler has no concept of objects or typed exceptions, it can't handle exceptions thrown by C++ code. However, C++ catch handlers can handle structured exceptions. C++ exception handling syntax (try, throw, catch) isn't accepted by the C compiler, but structured exception handling syntax (__try, __except, __finally) is supported by the C++ compiler.

See _set_se_translator for information on how to handle structured exceptions as C++ exceptions.

If you mix structured and C++ exceptions, be aware of these potential issues:

  • C++ exceptions and structured exceptions can't be mixed within the same function.

  • Termination handlers (__finally blocks) are always executed, even during unwinding after an exception is thrown.

  • C++ exception handling can catch and preserve the unwind semantics in all modules compiled with the /EH compiler options, which enable unwind semantics.

  • There may be some situations in which destructor functions aren't called for all objects. For example, a structured exception could occur while attempting to make a function call through an uninitialized function pointer. If the function parameters are objects constructed before the call, the destructors of those objects don't get called during stack unwind.

Next steps

See also

Modern C++ best practices for exceptions and error handling