如何在上下文管理器中捕获异常?

2024-10-03 15:24:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个例子,我需要捕获一些异常(在代码中,例如我想捕获ZeroDivisionError),并在我自己的上下文管理器中处理它。我需要检查此异常的计数并在控制台中打印。现在,当我运行代码时,我捕获了一次ZeroDivisionError,比我捕获的次数多

Traceback (most recent call last):
  File "/home/example.py", line 23, in foo
    a / b
ZeroDivisionError: division by zero

Process finished with exit code 1

例如:

class ExceptionCather:
    def __init__(
            self,
            try_counter,
            exc_type=None
    ):
        self.try_counter = try_counter

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        if exc_type == ZeroDivisionError:
            self.try_counter += 1
            if self.try_counter == 2:
                print(self.try_counter)


def foo(a, b):
    try_counter = 0
    while True:
        with ExceptionCather(try_counter):
            a / b


if __name__ == '__main__':
    foo(1, 0)

如何捕捉错误、在控制台中打印并继续使用脚本?我会感谢你的帮助


Tags: 代码self管理器iffoodeftypewith
1条回答
网友
1楼 · 发布于 2024-10-03 15:24:30

我不确定您想要实现什么,但是如果您想要处理ZeroDivisionError,只需从__exit__返回True

class ExceptionCather:
    def __init__(
            self,
            try_counter,
            exc_type=None
    ):
        self.try_counter = try_counter

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, tb):
        if exc_type == ZeroDivisionError:
            self.try_counter += 1
            if self.try_counter == 2:
                print(self.try_counter)
            return True  # This will not raise `ZeroDivisonError`


def foo(a, b):
    try_counter = 0
    while True:
        with ExceptionCather(try_counter):
            a / b


if __name__ == '__main__':
    foo(1, 0)

另外请注意,由于您处于while循环中,当您按Ctrl键停止循环时,KeyboardInterrupt将从ExceptionCatcher中引发ZeroDivisonError(因为__exit__在结束时没有返回True

相关问题 更多 >