如果出现异常,我希望程序捕获它们,记录它们,然后继续进行下一次迭代。显然仍然应该引发 KeyboardInterrupt 以便可以停止程序,但是我还应该引发任何其他异常吗?
下面是非常粗略的代码示例。这是一个捕获异常并记录它们的装饰器。基本上,我应该有任何其他异常(exception)
案例吗?
def exception_logger(func):
@wraps(func)
def wrapper(*args, **kwargs):
# Run as normal
try:
return func(*args, **kwargs)
except KeyboardInterrupt:
raise
# Any other exception that occurs is logged
except:
log_file = 'example.txt'
logger = logger_format(log_file)
logger.exception(f'\nAn exception occurred with: {func.__qualname__}\n')
print(f'\n\nAn exception occurred with: {func.__qualname__}\nView the log file for details.\n'.upper())
return wrapper
谢谢。
最佳答案
您应该只捕获Exception
,而不是使用 except:
,而不是黑名单(可能会老化)。它不包括 KeyboardInterrupt
和其他您不应该抑制的内容。 (记录它们可能没问题,但您似乎不想这样做。)另请参阅 advice against except: pass
in particular上下文。
关于python - 如果我想捕获并记录(而不是引发)异常,KeyboardInterrupt 应该是唯一引发的异常吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56705020/