Share via


Mixing C and C++ Exceptions

OverviewHow Do IFAQ

If you want to write more portable code, using structured exception handling in a C++ program is not recommended. However, you may sometimes want to mix C 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 cannot handle exceptions thrown by C++ code; however, C++ catch handlers can handle C exceptions. As such, C++ exception handling syntax (try, throw, catch) is not accepted by the C compiler, but structured exception handling syntax (__try, __except, __finally) is supported by the C++ compiler.

If you mix C and C++ exceptions, note the following:

  1. C++ exceptions and C exceptions cannot be mixed within the same function.

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

  3. C++ exception handling can catch and preserve unwind semantics in all modules compiled with the /GX compiler option (this option enables unwind semantics).

  4. There may be some situations in which destructor functions are not called for all objects. For example, if a C 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, those objects will not have their destructors called during stack unwind.

What do you want to know more about?