sys.exc_info() 的行为描述于蟒蛇文档 http://docs.python.org/2/library/sys.html and on SO https://stackoverflow.com/questions/1611561/python-error-handling-with-try-finally/1611572 and SO https://stackoverflow.com/questions/7375492/proper-care-and-safety-when-dealing-with-python-traceback-objects-from-sys-exc-i as:
- 在 except 块或 except 块调用的方法中,描述异常的三元组
- 在其他地方,三个 None 值
那么为什么这个鼻子测试会失败呢?
def test_lang_stack(self):
try:
self.assertEquals((None,None,None), sys.exc_info()) # no exception
a = 5 / 0
except:
self.assertNotEquals((None,None,None), sys.exc_info()) # got exception
else:
self.fail('should not get here')
#finally:
# self.assertEquals((None,None,None), sys.exc_info()) # already handled, right?
self.assertEquals((None,None,None), sys.exc_info()) # already handled, right?
它在最后一行失败。如果您取消注释finally块,它就会在那里失败。
我确实看到,如果我将所有这些放入一个方法中并从不同的方法调用,那么调用方法不会看到异常。 exc_info 值似乎仍然设置为抛出异常的方法的末尾,即使在处理异常之后也是如此。
我在 OSX 上使用 python2.7。