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 cannot 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 unwind semantics in all modules compiled with the /EH compiler options, which enable unwind semantics.

  • There may be some situations in which destructor functions are not called for all objects. For example, if a structured exception occurs while attempting to make a function call through an uninitialized function pointer, and that function takes as parameters objects that were constructed before the call, the destructors of those objects are not called during stack unwind.

Next steps

See also

Modern C++ best practices for exceptions and error handling