Skip to content

Latest commit

 

History

History
36 lines (22 loc) · 2.68 KB

mixing-c-structured-and-cpp-exceptions.md

File metadata and controls

36 lines (22 loc) · 2.68 KB
title description ms.date helpviewer_keywords ms.assetid
Mixing C (structured) and C++ exceptions
How to mix structured exception handling and C++ exceptions, and some potential issues.
08/24/2020
exceptions [C++], mixed C and C++
C++ exception handling, mixed-language
structured exception handling [C++], mixed C and C++
catch keyword [C++], mixed
try-catch keyword [C++], mixed-language
a149154e-36dd-4d1a-980b-efde2a563a56

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