为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

心有法竹 2022-09-06 16:21:37
我有案例,我需要捕获一些异常(例如在代码中,我想捕获)并在我自己的上下文管理器中处理它。我需要检查此异常的计数并在控制台中进行打印。现在,当我运行我的代码时,我有一次捕获,并且比我有ZeroDivisionErrorZeroDivisionErrorTraceback (most recent call last):  File "/home/example.py", line 23, in foo    a / bZeroDivisionError: division by zeroProcess 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 / bif __name__ == '__main__':    foo(1, 0)如何捕获错误,在控制台中打印并继续使用我的脚本?会很感激的帮助
查看完整描述

1 回答

?
largeQ

TA贡献2039条经验 获得超8个赞

我不确定你想实现什么,但如果你想处理,只需从中返回:ZeroDivisionErrorTrue__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 循环中,当你按 + 停止循环时,会从你的(因为没有在最后返回)引发。CtrlCKeyboardInterruptZeroDivisonErrorExceptionCatcher__exit__True


查看完整回答
反对 回复 2022-09-06
  • 1 回答
  • 0 关注
  • 125 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号