Can we in python code, catch exception generated by C++ pythonized function?

Alex Martelli aleaxit at yahoo.com
Tue Jan 9 08:15:52 EST 2001


"Siu-Tong Hui" <tong at aristotech.com> wrote in message
news:3A5A4545.661385AD at aristotech.com...
> I tried and it won't. Anybody have any workaround for that? Any pointer
> is appreciated. Thanks.

What you see on the Python level as a Python exception
is denoted by a C-level function returning NULL (a zero
pointer) rather than a PyObject* (a pointer to a PyObject),
as well as having made the appropriate PyErr_... calls
to define the details of the exception-object being
'raised'.  This is part of Python's C API.

"Exceptions" raised/handled by other protocols (such as,
C++ Exceptions, COM Exceptions, Win/NT SEH Exceptions,
and so on) have no a-priori connection with this specific
exception protocol.  You (or whatever framework you're
using to map your code to Python's C API) must bridge
the gap, if you want it to be bridged.

You're not telling us which (if any) framework (such as
Boost Python, CXX, etc) you may be using to map C++ code
to Python's C API, so, as a guess, you may be using the
raw C API from C++.  That's OK, but then you also need
to do the needed bridging at the raw C API level.


E.g., where you now have something like:

PyObject* myFunction(PyObject* self, PyObject* args)
{
    // lots and lots of code snipped
    return Py_BuildValue("");    // or whatever
}

you will instead have something like:

PyObject* myFunction(PyObject* self, PyObject* args)
{
    try {
        // lots and lots of code snipped
        return Py_BuildValue("");    // or whatever
    } catch(...) {    // more specific catch clauses work better
        // whatever PyErr... calls are appropriate
        return 0;
    }
}


Alex






More information about the Python-list mailing list