How do I throw an exception class from C?

Michael P. Reilly arcege at
Wed Aug 11 23:24:40 CEST 1999

Brad Clements <bkc at> wrote:
: In my swig'd module  I can easily throw an exception string or tuple, but
: how do I throw an exception class?

: I want to create a new exception type that is a class, create a class object
: with some init data, then set the exception for the current thread to that
: object.

: Easy in Python, hard in C. How do I do it?

: Thanks,

You've created your exception already which is good.  Now you need to set
the exception and return NULL instead of a Python object.

  PyObject *
  MyFunction(PyObject *self, PyObject *args)
      PyErr_SetString(MyException, "You can't do that");
      return NULL;

Returning NULL signals that an exception has been raised, and setting
the exception as above will save the exception info (a la
sys.exc_info).  You might want to read up on


More information about the Python-list mailing list