Search code examples
c++exceptionc-api

Passing exceptions across a C API boundary


I am writing a library in C++ which uses an older C API. The client of my library can specify callback functions, which are indirectly called through my library which is called through the C API. This means that all exceptions in the client callbacks must be handled.

My question is this: how can I catch the exception on one side of the boundary and re-throw it once the C API boundary has been recrossed and the execution is back in C++ land so that the exception can be handled by client code?


Solution

  • With C++11 we could use:

    std::exception_ptr active_exception;
    
    try
    {
        // call code which may throw exceptions
    }
    catch (...)
    {
        // an exception is thrown. save it for future re-throwing.
        active_exception = std::current_exception();
    }
    
    // call C code
    ...
    
    // back to C++, re-throw the exception if needed.
    if (active_exception)
        std::rethrow_exception(active_exception);
    

    Before C++11 these can still be used via Boost Exception.