gpt4 book ai didi

python 3。如何在上下文管理器中正确引发异常以使用运算符处理异常?

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:31 25 4
gpt4 key购买 nike

我想捕获上下文管理器内部引发的异常。我创建了简单的示例来重现该问题。

所以,我的上下文管理器:

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 捕获。如何解决这个问题?

最佳答案

错误是您的__exit__() 函数的实现。

文档指出:

returning a true value from this method will cause the with statement to suppress the exception and continue execution with the statement immediately following the with statement. Otherwise the exception continues propagating after this method has finished executing. Exceptions that occur during execution of this method will replace any exception that occurred in the body of the with statement.

只需删除

return self

来自 __exit__() 函数。没有返回将返回 None,其评估为 False

关于 python 3。如何在上下文管理器中正确引发异常以使用运算符处理异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com