Details on exceptions

Stian Søiland stain at
Sat Nov 22 21:04:05 CET 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
>>> b
>>> try:
...   raise MyError
... except Exception, error:
...   (x,y) = error
...   print x

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

This could even be simplified:

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

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  cars makes you an automotive engineer. [ESR]

More information about the Python-list mailing list