[C++-sig] Have error_already_set - now what?

Nat Goodspeed ngoodspeed at solidworks.com
Thu Jan 11 19:58:30 CET 2007


> -----Original Message-----
> From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org]
On
> Behalf Of Stefan Seefeld
> Sent: Thursday, January 11, 2007 1:00 PM
> To: Development of Python/C++ integration
> Subject: Re: [C++-sig] Have error_already_set - now what?
> 
> > try {
> >     ... some python call ...
> >     return 0;
> > } catch (error_already_set&) {
> >     assert(PyErr_Occurred());
> >     PyErr_Print();
> >     return -1;
> > }
> >
> > Sure enough I'm getting -1 back, but nothing is printed to stderr
AFAIK.

[Nat] Um, might PyErr_Occurred() be clearing the flag?

> > What's a good way to find out what error occurred (exhaustively
matching
> > doesn't strike me as good).
> 
> I believe at present you do need to use the Python C API to find out
> what kind of python exception is set, and then act appropriately.

[Nat] This is what we use:

        catch (error_already_set&)
        {
            PyObject *type, *value, *traceback;
            // Save the error state because PyErr_Print() is going to
clear
            // it. That's not what we want.
            PyErr_Fetch(&type, &value, &traceback);
            // But whoops, PyErr_Fetch() just cleared the exception
flag! If
            // we now call PyErr_Print(), it thinks there's nothing
wrong, and
            // doesn't print anything! Immediately restore the exception
so
            // PyErr_Print() will see it.
            PyErr_Restore(type, value, traceback);
            // Okay, print the traceback to stderr...
            PyErr_Print();
            // then restore (again!) the original exception state.
            PyErr_Restore(type, value, traceback);
            // Propagate the exception.
            throw;
        }
 
> It would be nice to have some boost::python API to encapsulate that,
> i.e. to query the exception type, object, and stack trace into
> boost::python
> objects.

[Nat] Sounds great to me!



More information about the Cplusplus-sig mailing list