Setting Exception data.
Martin von Loewis
loewis at informatik.hu-berlin.de
Sun Mar 11 15:50:15 EST 2001
Ivan Munoz <imunoz at eso.org> writes:
> When raising a foo.error exception In my C code I set the error object
> to some data (an object defined on my extension module, an integer and a
> string) as follows:
>
> v=Py_BuildValue("Ois", e, errorNumber, errStr);
> if (v != NULL) {
> PyErr_SetObject(ErrorObject, v);
> Py_DECREF(v);
> }
That may not exactly do what you expect. It first builds a tuple, and
then sets it as the exception. Python normalizes the exception,
essentially by doing
exc = ErrorObject(e,errorNumber,errStr)
i.e. it creates an instance by calling the class with the tuple as
arguments.
> so far so good, in Python then I catch this exception as:
>
> except foo.error, (object, errnum, errstr):
Here, you have an implicit instance-unpacking:
object,errnum,errstr = exc
Now, since exc is a class instance, this accesses exc[0],exc[1],exc[2]
subsequently, which then invokes __getitem__ three times.
> Now what is the right way to acomplish the same from Python?, this does
> not seem to work ....
>
> raise foo.error MyObject, errnum, 'You are toasted'
Please have a look at the raise syntax. It allows
raise Class
raise Class, Value
raise Value
raise Class, Value, Traceback
Value can be an instance of Class, a single value, or a tuple; in the
latter cases, an instance is constructed by calling the class. So you
can write either
raise foo.error(MyObject, errnum, 'You are toasted')
or
raise foo.error,(MyObject, errnum, 'You are toasted')
Hope this helps,
Martin
More information about the Python-list
mailing list