Search code examples
c++cfunctionexceptionundefined-behavior

Throwing C++ exception through C function call


I have three free functions: F0, F1 and F2. F0 calls F1, which in turn calls F2.

F0 and F2 are C++ functions, where as F1 is a C function. F2 is exposed to F1 via: extern "C"

The code for each of the free functions is as follows:

~~~~ F0.cpp ~~~~

void f0()
{
   try
   {
      f1();
   }
   catch (...)
   {}
}

~~~~ F0.cpp ~~~~


~~~~ F1.c ~~~~

void f1()
{
   f2();
}

~~~~ F1.c ~~~~


~~~~ F2.cpp ~~~~

void f2()
{
  throw 1
}

~~~~ F2.cpp ~~~~

Question:

Does the exception thrown in f2 progress through f1 and caught correctly in f0?

Or is std::unexpected invoked due to the exception not being handled, or is the whole thing supposed to be undefined behavior? - if so where in the standard does it talk about exception handling in this particular context.


Please note this is not about handling exceptions in C, but rather what happens in the situation where the exception can flow through the C layer (if at all) and be caught in the calling C++ layer - and any resulting side effects etc.


Solution

  • This is platform-specific and compiler-specific question.

    For example, on Linux/GCC, you have to compile C code with -fexceptions option, then unwind tables would be build and exception will go throw C code.

    From https://gcc.gnu.org/onlinedocs/gcc-7.3.0/gcc/Code-Gen-Options.html#index-fexceptions

    -fexceptions

    Enable exception handling. Generates extra code needed to propagate exceptions. For some targets, this implies GCC generates frame unwind information for all functions, which can produce significant data size overhead, although it does not affect execution. If you do not specify this option, GCC enables it by default for languages like C++ that normally require exception handling, and disables it for languages like C that do not normally require it. However, you may need to enable this option when compiling C code that needs to interoperate properly with exception handlers written in C++. You may also wish to disable this option if you are compiling older C++ programs that don’t use exception handling.

    I'm less familiar with Visual C++/Windows development, but I believe exceptions handling will use common mechanisms if you compile your C++ and C code with /EHa option (allow mix of structured and C++ exceptions)