Exception confusion
Martin von Loewis
loewis at informatik.hu-berlin.de
Wed Aug 8 07:41:10 EDT 2001
Martin Sjögren <martin at strakt.com> writes:
> Doesn't this strike anybody as inconsequent?
Not at all. Just be aware that
I. catching an exception is an assignment to the exception variable.
So if you write
.... raise x
except Y, z:
then just before the except block, the assignment
z = x
happens.
II.Exceptions support tuple unpacking
>>> e = Exception(1,2)
>>> a,b=e
>>> a
1
>>> b
2
[If you wonder how they do that: using __getitem__]
III. Raising an exception in the form klass,value is the same
as raising it as klass(value)
> I wrote this little test script:
>
> try: raise Exception, "foo"
> except Exception, arg: print type(arg)
This really is
arg = Exception("foo")
> try: raise Exception, "foo"
> except Exception, (arg,): print type(arg)
(arg,) = Exception("foo")
which is tuple unpacking.
> try: raise Exception, ("foo", "bar"):
> except Exception, (arg,): print type(arg)
>
Tuple unpacking, namely
(arg,) = Exception("foo", "bar")
This fails, because the exception has two elements, but you want to
unpack only a single one.
Hope this helps,
Martin
More information about the Python-list
mailing list