python 在上下文管理器中吞下异常并继续
我想编写一个上下文管理器,它可以吞掉给定的异常并继续。
class swallow_exceptions(object):
def __init__(self, exceptions=[]):
self.allowed_exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if exception_type in self.allowed_exceptions:
print(f"{exception_type.__name__} swallowed!")
return True
它按预期吞下 ZeroDivisonError,但随后由于 '__exit__' 方法中的 return True 语句而从 ContextManager 终止。
with swallow_exceptions([ZeroDivisionError]):
error_1 = 1 / 0
error_2 = float("String") # should raise ValueError!
有没有办法捕获异常然后继续?我尝试使用“yield True”,但它终止了,根本没有打印任何内容。
I want to write a context manager which can swallow the given exceptions and GO ON.
class swallow_exceptions(object):
def __init__(self, exceptions=[]):
self.allowed_exceptions = exceptions
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if exception_type in self.allowed_exceptions:
print(f"{exception_type.__name__} swallowed!")
return True
It swallows the ZeroDivisonError as expected but then it terminates from the ContextManager because of the return True statement in the '__exit__' method.
with swallow_exceptions([ZeroDivisionError]):
error_1 = 1 / 0
error_2 = float("String") # should raise ValueError!
Is there a way to catch the exception and then go on? I tried with 'yield True' but it terminated without printing anything at all.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在异常返回到上下文管理器后,无法继续运行
with
语句的主体。上下文管理器可以阻止异常进一步冒泡,但它不能做更多的事情。您可能想要在多个单独的
with
语句中使用上下文管理器:There's no way to continue running the body of the
with
statement after an exception makes it back to the context manager. The context manager can stop the exception from bubbling up further, but it can't do more than that.What you might want is to use your context manager in several separate
with
statements: