Handling custom C++ exceptions in Cython

c++, cython, exception

Solution

If `CustomLibraryException` derives from `std::runtime_error` (as a well-behaved C++ exception should), then the behavior you're seeing is a bug in Cython.

If it doesn't, then the easiest thing to do is to wrap the C++ function you're calling in a C++ helper function that translates the exception:

double foo(char const *, Bla const &);  // this is the one we're wrapping

double foo_that_throws_runtime_error(char const *str, Bla const &blaref)
{
    try {
        return foo(str, blaref);
    } catch (CustomLibraryException const &e) {
        throw std::runtime_error(e.get_the_message());
    }
}

This will cause a `RuntimeError` to be raised on the Python side. Alternatively, `throw` an `std::invalid_argument` to `raise` a `ValueError`, etc. (see the table in the page you linked to).

Problem

I have some trouble handling custom C++ exceptions when calling from Cython. My situation is the following: I have a library that uses `CustomLibraryException` for all exceptions. What I want is basically get the error message and raise a Python error with it. The user guide has some hints but it is a bit unspecific. The first possibility is to do: cdef int bar() except +ValueError This converts the `CustomLibraryException` to a `ValueError`, but loses the error message. The other possibility is to explicitly convert the error using ``` cdef int raise_py_error() cdef int something_dangerous() except +raise_py_error ``` I don't really understant this solution. I understood that raise_py_error has to be a C++ function that somehow handles the error. I am not sure how to handle it though. The function doesn't get an argument and is called inside the `catch` block in C++. If any one has an working example of handling a C++ exception in Cython, that would be of great help.

Original source