【问题标题】:If I want to catch and log (not raise) exceptions, should KeyboardInterrupt be the only raised exception?如果我想捕获并记录(不引发)异常,KeyboardInterrupt 应该是唯一引发的异常吗?
【发布时间】:2019-11-04 09:33:30
【问题描述】:

在出现异常的情况下,我希望程序捕获它们,记录它们,然后继续下一次迭代。显然,仍然应该引发 KeyboardInterrupt 以便可以停止程序,但是我应该引发任何其他异常吗?

下面是非常粗略的代码示例。这是一个装饰器,它捕获异常并记录它们。基本上,我应该还有其他except 案例吗?

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


谢谢。

【问题讨论】:

    标签: python python-3.x exception logging


    【解决方案1】:

    您应该只使用Exception 而不是使用except:,而不是黑名单(可能会老化)。它不包括KeyboardInterrupt 和其他你不应该压制的其他人。 (记录它们可能没问题,但无论如何您似乎都不想这样做。)另请参阅advice against except: pass in particular 了解上下文。

    【讨论】:

      猜你喜欢
      • 2019-03-11
      • 1970-01-01
      • 2014-07-17
      • 1970-01-01
      • 2013-11-11
      • 2010-09-10
      • 2012-02-05
      • 1970-01-01
      相关资源
      最近更新 更多