[C++-sig] try-except for non-standard exception

Håkon Groven hgroven at emgs.com
Tue Apr 15 16:17:28 CEST 2008


Hi!

I'm trying to expose my cpp-defined exception so that i can do something 
like this in Python:

try:
    value = someObject.someFunction()
except Pyelio.ElioError, e:
    print e.what()

I have tried to do the following in the cpp wrapper:

namespace
{
     struct emgs_elio_ElioError_Wrapper: ElioError
     {
         emgs_elio_ElioError_Wrapper(PyObject* py_self_, const 
ElioError& p0):
         ElioError(p0), py_self(py_self_)
         {}

         emgs_elio_ElioError_Wrapper(PyObject* py_self_):
         ElioError(), py_self(py_self_)
         {}

         emgs_elio_ElioError_Wrapper(PyObject* py_self_, const 
std::string& p0):
         ElioError(p0), py_self(py_self_)
         {}

         const char* what() const throw()
         {
             return call_method< const char* >(py_self, "what");
         }

         const char* default_what() const
         {
             return ElioError::what();
         }

         PyObject* py_self;
     };

     void translate(ElioError const& e)
     {
         PyErr_SetString(PyErr_NewException(
                 "Pyelio.ElioError",
                 PyExc_StandardError, NULL),
                 e.what());
     };
}

BOOST_PYTHON_MODULE(Pyelio)
{
    register_exception_translator<ElioError>(&translate();

     class_< ElioError, emgs_elio_ElioError_Wrapper >("ElioError", init< 
const ElioError& >())
     .def(init< optional< const std::string& > >())
     .def("what", (const char* (ElioError::*)() const 
throw())&ElioError::what, (const char* 
(emgs_elio_ElioError_Wrapper::*)() 
const)&emgs_elio_ElioError_Wrapper::default_what)
     .def("printStackTrace", &ElioError::printStackTrace)
     ;

}

Because of my translate function my exception is a standard error on the 
python side and not a Pyelio.ElioError. However, if i print type(e) in 
python I get the string from my translate func: "Pyelio.ElioError".

I would be very thankful if anybody could help me out/post a minimal 
example of how to wrap/expose a cpp-defined exception.

Hakon.



More information about the Cplusplus-sig mailing list