Catching user-defined exception types

30 views
Skip to first unread message

walt3k

unread,
Mar 11, 2024, 1:58:18 AMMar 11
to cython-users
I have a situation where, in a pyx file, I need to call a C++ function which can throw a user-defined exception class, not a std library type.  I see there is the except + syntax but based on the documentation, this is only for converting from the C++ std exception type to the equivalent Python type.

Is there no way to
try:
    some_c++_func()
except <some C++ cdef class> as e:
    e.some_user_defined_C++_method()

Seems like there's got to be a way to do this and not just what the doc shows which is:
Exceptions

Cython cannot throw C++ exceptions, or catch them with a try-except statement, but it is possible to declare a function as potentially raising an C++ exception and converting it into a Python exception. For example,

cdef extern from "some_file.h": cdef int foo() except +

This will translate try and the C++ error into an appropriate Python exception. The translation is performed according to the following table (the std:: prefix is omitted from the C++ identifiers):


C++
Python

bad_alloc
MemoryError
bad_cast
TypeError
domain_error
ValueError

(and so on)

walt3k

unread,
Mar 21, 2024, 4:22:17 PMMar 21
to cython-users
My apologies.  I was looking at old cython documentation.  This documentation shows how to use a custom exception handler which does what I asked.
https://cython.readthedocs.io/en/latest/src/userguide/wrapping_CPlusPlus.html#exceptions
Reply all
Reply to author
Forward
0 new messages