我有案例,我需要捕获一些异常(例如在代码中,我想捕获)并在我自己的上下文管理器中处理它。我需要检查此异常的计数并在控制台中进行打印。现在,当我运行我的代码时,我有一次捕获,并且比我有ZeroDivisionErrorZeroDivisionError
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)
如何捕获错误,在控制台中打印并继续使用我的脚本?会很感激的帮助
largeQ
相关分类