Reputation: 23921
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, that Python policy is to derive all exceptions from BaseException class. I know how to create a derived type object (assigning to tp_base memeber), but I don't know how to obtain a reference to BaseException type object. PyExc_BaseException is a reference to PyObject, representing a class, not a type object.
How do I throw custom Python exceptions from C code?
Upvotes: 15
Views: 3864
Reputation: 1
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
.
Upvotes: 0
Reputation: 602145
The easiest way to create a new exception type in C code is to call PyErr_NewException
.
Upvotes: 6