translating C++ exceptions to python

Denis S. Otkidach ods at strana.ru
Tue Jun 14 11:20:27 CEST 2005


On 13 Jun 2005 04:23:03 -0700
calin.hanchevici at gmail.com wrote:

> Hi all,
> 
> I have a C++ library I call from python. The problem is I have c++
> exceptions that i want to be translated to python. I want to be able to
> do stuff like:
> try:
>     my_cpp_function()
> except cpp_exception_1:
>     do_stuff
> except cpp_exception_2:
>     do_other_stuff
> 
> any ideas how can i do the translation?

1. Create Python class for your exception.  For simple case the code
will be:

static PyObject *YouExceptionClass;

# and in module initialization function:
YouExceptionClass =  PyErr_NewException("YourModule.YourException", 0, 0);

2. Add it to module dictionary.

3. In wrapper for my_cpp_function use something like the following 
code:

try {
    my_cpp_function_impl();
} catch (YouException &exc) {
    PyErr_SetString(YouExceptionClass, exc.what());
    return 0;
}

-- 
Denis S. Otkidach
http://www.python.ru/      [ru]



More information about the Python-list mailing list