[C++-sig] export custom C++ exception to Python so it can be raisedby python

Giuseppe Corbelli giuseppe.corbelli at copanitalia.com
Tue Nov 6 10:08:43 CET 2012


On 05/11/2012 18:51, Martin Hellmich wrote:
> Hi,
>
> I have a custom exception in C++ that I would like to use in Python.
>
> Let's call it MyException with custom constructor and members (an
> implementation is below).
> I would like to expose it to python so that I can raise it:
>
>  > raise MyException(-1, 'tragic error')
>
> The perfect way that I can imagine is to tell boost::python to base the class
> on PyExc_Exception, but that doesn't seem to work. Furthermore I have found
> various solutions how to translate exceptions thrown in C++ into proper Python
> exceptions, but in my case these solutions sit at the wrong place.

I've based my code on.
http://stackoverflow.com/questions/9620268/boost-python-custom-exception-class

> I would like to avoid to create a corresponding python class to the C++
> exception, because there would be added effort to keep the two descriptions
> consistent.

True.

> class MyException: public std::exception {
> MyException();
> MyException(int code, const std::string &string);
>
> int code();
> const char* what();
>
> int errorCode;
> std::string errorMessage;
> };

The only unusual stuff is that you need both code and message. 2 ideas come to 
mind.
1) you can base the python exception not on PyExc_Exception but on a custom 
class which can handle both error code and message, so the exception 
translator can do both a PyErr_SetString and a "PyErr_SetCode". This way you 
can use the exception in both C and Python in the same style, no need to keep 
anything in sync.

2) you can base the Python exception on the standard PyExc_Exception but use 
PyErr_SetObject in the exception translator. A quick search finds this
http://stackoverflow.com/questions/2261858/boostpython-export-custom-exception
(does not inherit from Exception, though)

-- 
             Giuseppe Corbelli
WASP Software Engineer, Copan Italia S.p.A
Phone: +390303666318  Fax: +390302659932
E-mail: giuseppe.corbelli at copanitalia.com


More information about the Cplusplus-sig mailing list