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

标签 python error-handling contextmanager

我遇到的情况是,我需要捕获一些异常(例如,在代码中,我想捕获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)

如何捕获错误,在控制台中进行打印并继续执行脚本?会很感激的

最佳答案

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

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 + C停止循环时,会引发KeyboardInterrupt,这会从ZeroDivisonError中引发ExceptionCatcher(因为__exit__最后没有返回True)。

关于python - 如何在上下文管理器中捕获异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60765584/

相关文章:

python - 向结构化numpy数组添加字段(二)

sql-server - 将错误写入日志后退出脚本

vue.js - 未定义Vue.js引用错误(event.target)

python - 使用 threading.Lock 作为上下文管理器

python - 使用可变数量的上下文管理器替代 contextlib.nested

python - Cythonise 一个 pandas 循环

python - 如何使用 environtment.yml 文件使用 pip 将本地库安装到 conda 环境?

python - 使用 Python 的 lambda 函数排列字符串的数量

java - 使用斯坦福解析器解析凌乱的文本

Python:为什么我会收到 AttributeError:__enter__