Details on exceptions

Stian Søiland stain at stud.ntnu.no
Sat Nov 22 15:04:05 EST 2003


* Derek Fountain spake thusly:
> exception object just before the exception handler executes". This doesn't
> make sense in this case:
> except IOError, (errno, strerror):

Maybe this could illustrate why this works:

>>> class MyError(Exception):
...     def __getitem__(self, pos):
...         if pos > 1:
...             raise IndexError
...         return pos
...
>>> err = MyError()
>>> a,b = err
>>> a
0
>>> b
1
>>> try:
...   raise MyError
... except Exception, error:
...   (x,y) = error
...   print x
...
0      

So if error by any chance implements __getitem__ - the 
current case of IOError and actually all Exceptions, values might be
unpacked.

This could even be simplified:

>>> try:
...   raise Exception(5,6)
... except Exception, (a,b):
...   print a
...
5


Ie. the items of an exceptions are the arguments given when it is
raised. If you know how a exception is raised, ie. that an IOError
always contains two elements, you might unpack.

Remember that what actually happens in this line:
    except Exception, error:
is the assignment error = errorInstance

If one instead writes:
    except Exception, (a,b):
this simply means assignment unpacking:
    (a,b) = errorInstance



-- 
Stian Søiland               Being able to break security doesn't make
Trondheim, Norway           you a hacker more than being able to hotwire
http://stain.portveien.to/  cars makes you an automotive engineer. [ESR]




More information about the Python-list mailing list