[C++-sig] PyErr_ExceptionMatches not working?
Lawrence Spector
Lawrence.Spector at CanfieldSci.com
Fri Jul 20 00:13:12 CEST 2007
Ahh, I didn't realize that fetching caused the exception to clear. Now I've corrected it, done a quick test, and it works.
Thanks for the help,
Lawrence
-----Original Message-----
From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Nat Goodspeed
Sent: Thursday, July 19, 2007 6:01 PM
To: Development of Python/C++ integration
Subject: Re: [C++-sig] PyErr_ExceptionMatches not working?
________________________________________
From: c++-sig-bounces at python.org [mailto:c++-sig-bounces at python.org] On Behalf Of Lawrence Spector
Sent: Wednesday, July 18, 2007 3:11 PM
To: Development of Python/C++ integration
Subject: [C++-sig] PyErr_ExceptionMatches not working?
I have code that checks the following (snippet) when an exception is thrown...
if (PyErr_ExceptionMatches(PyExc_NameError))
{
// do something...
}
It doesn't get into that block, yet, when I do this:
PyErr_Fetch(&errObj, &errData, &errTraceback);
std::cout << "Object error" << PyString_AsString(PyObject_Str(errObj));
I get:
Object error: <type 'exceptions.NameError'>
What gives? Why isn't PyErr_ExceptionMatches saying that it's a NameError? Does Boost.Python provide a better way to do exception handling than the Python API directly?
[Nat] I'm unaware of any Boost.Python enhancements to Python exception handling, though I think I remember seeing a mail message indicating interest among the developers.
Do you do your PyErr_Fetch() before your PyErr_ExceptionMatches()? Beware that fetching the Python exception clears the exception condition. Here's some code we use to print a Python exception without suppressing it:
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;
}
_______________________________________________
C++-sig mailing list
C++-sig at python.org
http://mail.python.org/mailman/listinfo/c++-sig
More information about the Cplusplus-sig
mailing list