Weird exception handling behavior -- late evaluation in except clause

Terry Reedy tjreedy at
Sun Dec 2 21:46:02 CET 2012

On 12/2/2012 12:25 PM, 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 :-(

You would have the same problem if you spelled the exception name right 
but misspelled a name in the corresponding block. This is PyLint, 
PyChecker, xxx territory.

Note that proper checking requires execution of imports.

import mymod

try: pass
except mymod.MymogException: pass  # whoops

> 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.

'try:' is very cheap. Searching ahead any checking names in all the 
except clauses would be much more expensive -- and useless after the 
first time the code is run after being revised.

Terry Jan Reedy

More information about the Python-list mailing list