[C++-sig] Re: Wrapper for exception translation

gritsch at iue.tuwien.ac.at gritsch at iue.tuwien.ac.at
Thu Apr 14 09:27:07 CEST 2005


Hi,

I am also looking forward to some nice mechanism to integrate custom exceptions
nicely with Boost.Python.  However, in the meantime I use the following
approach, and I wonder, if this is currently the correct way:

--- 8< ---

#include <string>
#include <boost/python.hpp>

struct MyException {
   std::string what() const {
        return "MyException occurred";
    }
};

void throw_it() {
    throw MyException();
}

static PyObject * my_exception = NULL;

void translator( MyException const & e ) {
    PyErr_SetString( my_exception, e.what().c_str() );
}

BOOST_PYTHON_MODULE( extest ) {
    my_exception = PyErr_NewException( "extest.MyException", NULL, NULL );
    PyModule_AddObject( boost::python::scope().ptr(), "MyException",
my_exception );
    boost::python::register_exception_translator<MyException>( translator );

    boost::python::def( "throw_it", throw_it );
}

--- 8< ---

Do I really have to use the Python C-API funcions
  PyErr_NewException and
 PyModule_AddObject



----------------------------------------------------------------
This message was sent using IMP, the Internet Messaging Program.



More information about the Cplusplus-sig mailing list