Detecting an active exception

NeBlackCat (lists) lists at asd-group.com
Fri Jun 1 12:09:58 EDT 2007


Hello everybody - my first post! And it may be the most monumentally 
stupid question ever asked, but I just can't see an answer after several 
hours experimenting, searching and reading.

It's simply this - how can a function determine whether or not it's 
being called in handling of an exception (ie. there is an "active" 
exception, and somewhere upstream on the stack there is an except: block 
statement)?

Depending on what you read, sys.exc_info() is supposed to return 
(None,None,None) when there is no active exception, but it seems that it 
returns info about the last exception when there isn't one currently 
active.

For example:

try:
    a = a + 1
except:
    pass

print sys.exc_info()

produces:
<class exceptions.NameError at 0x009648D0>, <exceptions.NameError 
instance at 0x00B5E508>, <traceback object at 0x00B5E4E0>

Where the traceback object identifies the offending a=a+1 line (of course).

Is there another way of doing this? Note that I can't rely on using 
sys.exc_clear() in any solution, unfortunately.

cheers

- John




More information about the Python-list mailing list