我想撰寫一個背景關系管理器,它可以吞下給定的例外并繼續。
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”,但它終止了,根本沒有列印任何東西。
uj5u.com熱心網友回復:
with在例外回傳背景關系管理器之后,無法繼續運行陳述句的主體。背景關系管理器可以阻止例外進一步冒泡,但它不能做更多的事情。
您可能想要的是在幾個單獨的with陳述句中使用您的背景關系管理器:
suppress = swallow_exceptions([ZeroDivisionError])
with suppress:
1 / 0 # this exception is suppressed
with suppress:
float("String") # this one is not
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/437712.html
上一篇:為什么運行此代碼時出現錯誤?
