1 回答

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
添加回答
舉報