Basilevs
Basilevs

Reputation: 23921

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, 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

Answers (2)

Leo Quensel
Leo Quensel

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

Sven Marnach
Sven Marnach

Reputation: 602145

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

Upvotes: 6

Related Questions