changing exceptions in C code

T

Thomas Heller

I'm calling into Python code from C with PyObject_CallObject(). If the
python function raises an exception, the above code returns NULL, and I
want to print out the exception with PyErr_Print().

For whatever reasons, I want to prepend a short string "(in callback)"
to the error message itself:

result = PyObject_CallObject(callable, arglist);
if (!result) {
Extend_Error_Info("(in callback)");
PyErr_Print();
}

I figured out this code for the Extend_Error_Info function:

void Extend_Error_Info(char *fmt, ...)
{
va_list vargs;
PyObject *tp, *v, *tb, *s;

va_start(vargs, fmt);
s = PyString_FromFormatV(fmt, vargs);
va_end(vargs);
if (!s)
return;

PyErr_Fetch(&tp, &v, &tb);
PyErr_NormalizeException(&tp, &v, &tb);
PyString_ConcatAndDel(&s, PyObject_Str(v));
Py_DECREF(v);
PyErr_Restore(tp, s, tb);
}

Does this look ok by the experts?

TIA,

Thomas
 
R

Rick L. Ratzel

If you're simply interested in adding info to the printed traceback,
then this would be easier:

result = PyObject_CallObject(callable, arglist);
if (!result) {
fprintf(stderr, "(in callback)");
PyErr_Print();
}

PyErr_Print() is just printing to stderr...you should be able to do
the same. If you're really needing to prepend to the actual traceback
object though, then your approach is probably the way to go.

-Rick Ratzel
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,197
Messages
2,571,038
Members
47,633
Latest member
BriannaLyk

Latest Threads

Top