Extension types as exceptions (Wrapup)
Michael P. Reilly
arcege at shore.net
Mon Aug 16 13:07:20 EDT 1999
Daniel Dittmar <daniel.dittmar at sap-ag.de> wrote:
: 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
You could probably also do:
PyObject *exc_args;
exc_args = Py_BuildValue("is", code, msg);
PyErr_SetObject(ErrorType, exc_args);
If the data isn't an exception instance, it creates one with the data
given.
As a good tip, return (PyObject *)NULL in your function, this lets you
use in your code:
return raiseError(27, "I don't know what happened");
instead of:
{ raiseError(27, "I don't know what happened");
return NULL;
}
-Arcege
More information about the Python-list
mailing list