Should I always call PyErr_Clear() when an exception occurs?

Jaime Wyant programmer.py at gmail.com
Tue Dec 21 00:28:28 EST 2004


I've found that the code below will crash if I don't have the
PyErr_Clear() function call.  Should I always call PyErr_Clear()?  The
error message I get has to do with garbage collection -->

Exception exceptions.ImportError: 'No module named badmodule' in 'garbage collec
tion' ignored
Fatal Python error: unexpected exception during garbage collection

/* Code that fails if PyErr_Clear() is removed */
#include "python.h"

int main()
{
  PyObject *pName, *pModule;
  int i;
  
  Py_Initialize();
  for (i = 0 ; i < 30; i++) {
    // First, import the module
    pName = PyString_FromString("badmodule");
    pModule = PyImport_Import(pName);
    Py_DECREF(pName);
    if (!pModule)
      {
        fprintf(stderr, "couldn't import badmodule\n");
        PyErr_Clear();
      }
    }
  
  Py_Finalize();
}

/* End code */

Thanks,
jw



More information about the Python-list mailing list