File: class/Workbook/Examples/Lecture16/pyerrors.c
#include <Python.h> #include <stdio.h> char save_error_type[1024], save_error_info[1024]; PyerrorHandler(char *msgFromC) { /* process Python-related errors */ /* call after Python API raises an exception */ PyObject *errobj, *errdata, *errtraceback, *pystring; printf("%s\n", msgFromC); /* get latest python exception info */ PyErr_Fetch(&errobj, &errdata, &errtraceback); pystring = NULL; if (errobj != NULL && (pystring = PyObject_Str(errobj)) != NULL && (PyString_Check(pystring)) ) strcpy(save_error_type, PyString_AsString(pystring)); else strcpy(save_error_type, "<unknown exception type>"); Py_XDECREF(pystring); pystring = NULL; if (errdata != NULL && (pystring = PyObject_Str(errdata)) != NULL && (PyString_Check(pystring)) ) strcpy(save_error_info, PyString_AsString(pystring)); else strcpy(save_error_info, "<unknown exception data>"); Py_XDECREF(pystring); printf("%s\n%s\n", save_error_type, save_error_info); Py_XDECREF(errobj); Py_XDECREF(errdata); /* caller owns all 3 */ Py_XDECREF(errtraceback); /* already NULL'd out */ }