Weird exception handling behavior -- late evaluation in except clause

Hans Mulder hansmu at xs4all.nl
Sun Dec 2 18:53:10 CET 2012


On 2/12/12 18:25:22, Roy Smith wrote:
> This is kind of weird (Python 2.7.3):
> 
> try:
>     print "hello"
> except foo:
>     print "foo"
> 
> prints "hello".  The problem (IMHO) is that apparently the except clause 
> doesn't get evaluated until after some exception is caught.  Which means 
> it never notices that foo is not defined until it's too late.
> 
> This just came up in some code, where I was trying to catch a very rare 
> exception.  When the exception finally happened, I discovered that I had 
> a typo in the except clause (I had mis-spelled the name of the 
> exception).  So, instead of getting some useful information, I got an 
> AttributeError :-(
> 
> Is this a bug, or intended behavior?  It seems to me it would be much 
> more useful (if slightly more expensive) to evaluate the names of the 
> exceptions in the expect clause before running the try block.

It's intended behaviour: Python runs your script from top to bottom.
It doesn't peek ahead at except: clauses.  Even it an exception is
raised, the exception names are not eveluated all at once.  Python
begins by evaluating the first exception name.  It the exception at
hand is an instance of that, Python has found a match and the rest
of the names are left unevaluated:

>>> try:
...  1/0
... except ZeroDivisionError:
...  print "hello"
... except 1/0:
...  pass
...
hello

There's probably some lint-like tool that can find this kind of issue.


Hope this helps,

-- HansM



More information about the Python-list mailing list