python 在上下文管理器中吞下异常并继续

发布于 2025-01-09 15:28:34 字数 721 浏览 3 评论 0原文

我想编写一个上下文管理器,它可以吞掉给定的异常并继续。

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

佞臣 2025-01-16 15:28:34

在异常返回到上下文管理器后,无法继续运行 with 语句的主体。上下文管理器可以阻止异常进一步冒泡,但它不能做更多的事情。

您可能想要在多个单独的 with 语句中使用上下文管理器:

suppress = swallow_exceptions([ZeroDivisionError])

with suppress:
    1 / 0              # this exception is suppressed

with suppress:
    float("String")  # this one is not

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:

suppress = swallow_exceptions([ZeroDivisionError])

with suppress:
    1 / 0              # this exception is suppressed

with suppress:
    float("String")  # this one is not
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文