except clause not catching IndexError

Steven D'Aprano steve at REMOVEMEcyber.com.au
Thu Feb 23 01:45:11 EST 2006


Erwin S. Andreasen wrote:

> Did you by any chance do something like:
> 
> except ValueError, IndexError:
> 
> at some point earlier in this function? That, when catching ValueError
> assigns the resulting exception to IndexError (and so the following
> except IndexError: wouldn't work as IndexError is no longer what you
> think it is). The correct syntax for catching multiple exceptions is:
> 
> except (ValueError, IndexError), targetVariable:


You mean to say that "except X,Y:" gives different 
results to "except (X,Y):"?

That can't be good.

 >>> try:
...     L = []; print L[2]
... except ValueError, IndexError:
...     print "Error!"
...
Traceback (most recent call last):
   File "<stdin>", line 3, in ?
IndexError: list index out of range

 >>> try:
...     L = []; print L[2]
... except (ValueError, IndexError):
...     print "Error!"
...
Error!


And here I was thinking that commas make tuples, not 
brackets. What is happening here?


-- 
Steven.




More information about the Python-list mailing list