[C++-sig] Howto expose exception classes using boost.python?

Juho Mäkinen juho.makinen at gmail.com
Tue Apr 25 21:39:08 CEST 2006


I have stumbled across this problem when I started looking the right
way how to expose a bunch of C++ Exception classes to python.

I have a "master" exception class, which is delivered from
std::exception. All other exception classes in our project are base on
this.

As far as I know, Python requires that the exceptions must be
delivered from PyExc_Exception, or a class which is delivered from
PyExc_Exception, but I haven't found any way how to expose a C++ class
which delivers from a python class. There's also PyErr_NewException()
available within Python C API.

This would be the ideal way how I'd like to use our exceptions.

PyErr_SetObject(PyExc_MyException,  InstanceOfMyException)
-or in python-
raise mymodule.MyException(arg1, arg2)

I know that I can expose C++ exceptions with boost.python (the
PodBayDoorException example) using
boost::python::register_exception_translator, but I want to be able to
distinguish my different C++ exceptions at the python side. (eg. It's
not enough that all my exceptions are translated into
PyExc_RuntimeError, or some other standard python exception)

All ideas how to expose exception hierarchy from C++ to Python are appreciated.

Thanks in advance,

 - Juho Mäkinen



More information about the Cplusplus-sig mailing list