如何在不阻塞执行的情况下处理Python中的异常?

时间:2014-04-11 14:13:17

标签: python

让我们说在我的(长)程序中有多个类/模块/文件,我有一个零错误除法,我在try ... except块中没有处理。如您所知,此错误将阻止我的程序。

有没有办法登录文件这个错误我忘记处理以便以后在检查错误日志文件时更正我的程序?

1 个答案:

答案 0 :(得分:1)

尝试/捕获/最后不是更好?

if __name__ == '__main__':
  try:
    #my code
  catch:
    exc_logger.exception('Guys, can we fix this?')

如果您想获得花哨和使用/滥用语言功能,可以在代码中放置错误上下文捕获器:

class ExceptionRecorder(object):
  def __init__(self, exc_logger):
    self.exc_logger = exc_logger

  def __enter(self):
    pass

  def __exit__(self, exc_type, exc_value, traceback):
    if exc_value:
      self.exc_logger.error('Program terminated with the following: ', exc_value)

    return True

并在你的主要:

if __name__ == '__main__':
  with ExceptionRecorder(logger.getLogger('oh_no')):
    #run the program code here

了解Context Managers的工作原理,特别是__exit__ method