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

Martin Hellmich mhellmic at cern.ch
Mon Nov 5 18:51:44 CET 2012


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

I am happy about any comments and questions!

Cheers
Martin


class MyException: public std::exception {
   MyException();
   MyException(int code, const std::string &string);

   int code();
   const char* what();

   int errorCode;
   std::string errorMessage;
};


More information about the Cplusplus-sig mailing list