Extension types as exceptions (Wrapup)
Daniel Dittmar
daniel.dittmar at sap-ag.de
Mon Aug 16 08:18:29 EDT 1999
Thanks for the help,
for those with similar problems, code to create the exception type
follows:
static PyObject *
createExceptionKind (
const char * exceptionName,
const char * exceptionCode)
{
PyObject * result;
PyObject * runResult = NULL;
PyObject * globals = NULL;
PyObject * locals = NULL;
if (exceptionCode != NULL) {
globals = PyDict_New ();
locals = PyDict_New ();
runResult = PyRun_String ((char *) exceptionCode,\
Py_file_input,
globals, locals);
}
result = PyErr_NewException ((char *) exceptionName, \
NULL,locals);
Py_XDECREF (locals);
Py_XDECREF (globals);
Py_XDECREF (runResult);
return result;
}
Parameter exceptionName is something of the form "mymod.ExceptionName"
Parameter exceptionCode is something like
"def __str__ (self):\n return 'ExceptionName: %d %s' % (self.code,
self.msg\n"
Error handling is a bit weak as I call this from module
initialization, which does it's own checking
Code to create a new exception:
static void
raiseError (
int code,
const char * msg)
{
PyObject * exception = PyInstance_New (ErrorType, NULL, NULL);
if (exception == NULL) {
return;
}
PyObject_SetAttrString(exception,"code", PyInt_FromLong (code));
PyObject_SetAttrString(exception,"msg", PyString_FromString(msg));
PyErr_SetObject (ErrorType, exception);
}
ErrorType is a c module static which contains the result of
createExceptionKind
More information about the Python-list
mailing list