【发布时间】:2014-07-07 16:42:48
【问题描述】:
考虑以下代码:
class Test(object):
def __enter__(self):
pass
def __exit__(self,type,value,trace):
if type:
print "Error occured: " + str(value.args)
#if I changed the next line to 'return True', the
#'print "should not happen"' statements are executed, but the
#error information would be only printed once (what I want)
return False
return True
with Test():
with Test():
with Test():
raise Exception('Foo','Bar')
print "should not happen"
print "should not happen"
示例输出:
发生错误:('Foo', 'Bar')
发生错误:('Foo', 'Bar')
发生错误:('Foo', 'Bar')
我有几个嵌套的with 语句,并且想要处理代码中某处引发异常的情况。我想要实现的是停止执行(上例中没有“不应该发生”的输出),但错误信息只打印一次。因此,我需要以某种方式知道是否已经处理了相同的错误。
您知道如何实现这一目标吗?
【问题讨论】:
标签: python python-2.7 exception-handling with-statement contextmanager