Re: [C++-sig] Handling a custom C++ exception from Python
On Sun, 02 Jun 2013 21:04:51 +0100, Александров Петр <petr_aleksandrov@mail.ru> wrote:
02.06.2013 13:14, Alex Leach пишет:
1. Boost Python has a dedicated exception handling API[1] that doesn't require you to wrap the exception in a class_<> template. The class_ template is a bit heavy duty for registering exceptions, I think. Instead, I register exceptions like this:-
#include <boost/python/exception_translator.hpp>
void TranslateMyException(const MyException& err) { PyErr_SetString(PyExc_Exception, err.ptr()); }
void RegisterMyExceptionTranslator(void) { boost::python::register_exception_translator< MyException&>( TranslateMyException ); } I want to pass some info (it is numbers) from C++ to Python with the exception. This info is stored in C++ exception object fields. Using class_ I allow accessing these fields from Python.
Well, that is one way to do it. Above, in TranslateMyException, you can do whatever you like with the C++ exception, though. I've been doing it that way,usually just creating a human-readable message from the C++ exception, then using the above mechanisms to set the exception for Python. To give your exception extra Python attributes, you might consider using the raw Python C API function, PyErr_NewException[1]. Your call, though. Cheers, Alex [1]: http://docs.python.org/2/c-api/exceptions.html#PyErr_NewException
participants (1)
-
Alex Leach