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.
If
CustomLibraryExceptionderives fromstd::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:
This will cause a
RuntimeErrorto be raised on the Python side. Alternatively,throwanstd::invalid_argumenttoraiseaValueError, etc. (see the table in the page you linked to).