Skip to content Skip to sidebar Skip to footer

How To Create A Custom Python Exception Type In C Extension?

I'm writing a Python module in C. I need to report errors that can't be described by built-in Python exceptions. I therefore wish to throw exceptions of my own type. The problem is

Solution 1:

The easiest way to create a new exception type in C code is to call PyErr_NewException.

Solution 2:

I managed to set tp_base by using (PyTypeObject*)PyExc_BaseException as the value, which results in my custom exception being properly inherited from BaseException.

There are some good hints in the CPython source code in exceptions.c.

Post a Comment for "How To Create A Custom Python Exception Type In C Extension?"