[capi-sig] Exceptions with additional instance variables
chojrak11 at gmail.com
chojrak11 at gmail.com
Mon Dec 22 13:06:17 CET 2008
On Mon, Dec 22, 2008 at 03:29, Guilherme Polo <ggpolo at gmail.com> wrote:
> On Sun, Dec 21, 2008 at 11:02 PM, <chojrak11 at gmail.com> wrote:
>> Hello,
>>
>> I'm trying to implement custom exception that have to carry some
>> useful info by means of instance members, to be used like:
>>
>> try:
>> // some code
>> except MyException, data:
>> // use data.errorcode, data.errorcategory, data.errorlevel,
>> data.errormessage and some others
>>
>> The question is - how to implement the instance variables with
>> PyErr_NewException?
>
> Using PyErr_NewException is fine. You must understand that an
> exception is a class, and thus PyErr_NewException creates one for you
> and returns it.
> Just like you would do with a class that has __dict__, set some
> attributes to what you want. That is, use PyObject_SetAttrString or
> something more appropriated for you.
Ok so I did the following. In init function (forget refcounting and
error checking for a moment ;-)
PyObject *dict = PyDict_New();
PyDict_SetItemString(dict, "errorcode", PyInt_FromLong(0));
static PyObject *myexception =
PyErr_NewException("module.MyException", NULL, dict);
PyModule_AddObject(module, "MyException", myexception);
It worked more or less as expected, the help shown:
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| errorcode = 0
|
| ----------------------------------------------------------------------
Then I did the following when raising the exception:
PyObject_SetAttrString(myexception, "errorcode", PyInt_FromLong(111));
PyErr_SetString(myexception, "Bad thing happened");
return NULL;
and the test code was:
try:
do_bad_thing();
except MyException, data:
and you surely already guessed it -- data.errorcode was 0.... Not only
that, module.MyException.errorcode was also 0...
What I'm doing wrong? I certainly don't get the idea of exceptions in
Python, especially what is being raised - a class or an instance? If
the latter - how's the class instantiated? If not - what about values
in different threads? The docs are so vague about that...
Thanks again in advance,
Chojrak
More information about the capi-sig
mailing list