亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在上下文管理器中捕獲異常?

如何在上下文管理器中捕獲異常?

心有法竹 2022-09-06 16:21:37
我有案例,我需要捕獲一些異常(例如在代碼中,我想捕獲)并在我自己的上下文管理器中處理它。我需要檢查此異常的計數并在控制臺中進行打印?,F在,當我運行我的代碼時,我有一次捕獲,并且比我有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 關注
  • 114 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號