September 27, 2007

Note to self: exc_info is only available after except handler

It looks wrong to me, but in Python an exception is registered only when it hits the except handler, not immediately after it's thrown. In the following code snippet the first finally block is totally unaware of the exception.
import sys
try:
try:
try:
raise SystemExit()
finally:
print "1:", sys.exc_info()
except:
print "2:", sys.exc_info()
raise
finally:
print "3:", sys.exc_info()
prints
1: (None, None, None)
2: (<class exceptions.SystemExit ... )
3: (<class exceptions.SystemExit ... )
This is not how I would expect it to work.

Upon closer inspection of the sys module's documentation:

exc_info()
This function returns a tuple of three values that give information about the exception that is currently being handled.
Here, 'handling an exception' is defined as 'executing or having executed an except clause.'
This contradicts to my common sense, but it is the way it is, so I'll have to find another solution for the problem at hand.


No comments: