【发布时间】:2019-10-28 11:15:59
【问题描述】:
我想捕获在上下文管理器中引发的异常。我创建了一个简单的例子来重现这个问题。
所以,我的上下文管理器:
class Test(object):
def div(self, a, b):
return a // b
def __enter__(self):
print('enter')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit')
return self
以及我想使用它的类:
class Container(object):
def test_exc(self, a, b):
try:
with Test() as test:
try:
result = test.div(a, b)
print(a, '/', b, '=', result)
return result
except Exception as e:
raise e
except Exception as e:
print(e)
用法:
c = Container()
c.test_exc(5, 1)
c.test_exc(5, 0)
输出:
enter
5 / 1 = 5
exit
enter
exit
因此,当引发异常时(在上面的示例中为 ZeroDivisionError),它不会被父级 try...catch 捕获。如何解决这个问题?
【问题讨论】:
标签: python python-3.x exception contextmanager