15

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?

2
  • 2
    A (new-style) class and a type object are the same thing in Python, so I don't understand your problem. Commented Jun 20, 2011 at 12:25
  • Sven, I've casted PyExc_RuntimeError and used it as the base type for my own Exception. So far nothing bad happened (I believe segfaults after long run are caused by something else). Could you answer my question, so I can accept your answer? Commented Jun 23, 2011 at 3:56

2 Answers 2

6

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

Sign up to request clarification or add additional context in comments.

3 Comments

How do I add members to objects of resulting class? I'd like to store error code somwhere in the excetion object.
@Basilevs: You can pass the constructor arguments for your exception to PyErr_SetObject(). The constructor of BaseException simply stores the argument tuple in the args attribute. If you want a different behaviour, overwrite the constructor.
Then how can python side access this value? I like parsing args tuple. What I need is extra member function in the raised object. If dict argument of PyErr_NewException is supposed to store extra functions, how do I create a new member functions from Python side?
0

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.

1 Comment

This didn't work for me because PyExc_BaseException is not a compile-time constant. Did you have some way to get around that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.