有什么优雅的方法可以在python中抽象出重复的异常处理?

时间:2011-03-21 06:06:43

标签: python exception-handling

在python中处理异常时,我发现自己经常重复代码。基本模式是这样的形式:

try:
  action_here()
except CommonException1:
  Action_always_taken_for_CommonException1()
except CommonException2:
  Action_always_taken_for_CommonException2()
except Exception:
  Default_action_always_taken()

我想要做的是如何将这些重复代码抽象出一个函数或类。我知道一种方法是使用异常对象调用异常处理函数,例如:

try:
  action_here()
except Exception as e:
  handle_exception(e)

然后在此函数中根据类确定异常。

def handle_exception(e):
  if type(e) == type(CommonException1()):
    Action_always_taken_for_CommonException1()
  elif type(e) == type(CommonException2()):
    Action_always_taken_for_CommonException2())
  else:
    Default_action_always_taken()
然而,这种感觉很笨拙而且不够优雅。所以我的问题是,处理重复异常处理还有哪些其他选择?

3 个答案:

答案 0 :(得分:19)

这种情况是上下文管理器和with语句的主要用例之一:

from __future__ import with_statement # Needed in 2.5, but not in 2.6 or later

from contextlib import contextmanager

@contextmanager
def handle_exceptions():
    try:
        yield # Body of the with statement effectively runs here
    except CommonException1:
        Action_always_taken_for_CommonException1()
    except CommonException2:
        Action_always_taken_for_CommonException2()
    except Exception:
        Default_action_always_taken()

# Used as follows
with handle_exceptions():
    action_here()

答案 1 :(得分:6)

如果您不喜欢重复的if / elseif块,可以将句柄放入dict中,键入类型:

handlers = { type(CommonException1()) : Action_always_taken_forCommonException1,
             type(CommonException2()) : Action_always_taken_forCommonException2 }

def handle_exception(te):
  if te in handlers:
    handlers[te]()
  else:
    Default_action()

然后你可以运行:

try:
  action_here()
except Exception as e:
  handle_exception(type(e))

此外:如果您发现自己经常编写这些try块,那么您可以编写自己的上下文管理器(请参阅here)。在action_here()方面,您的代码将如下所示:

with my_error_handling_context():
  action_here1()
  action_here2()

在这种情况下,handle_exception代码基本上是您的上下文管理器的__exit__方法(总是会传递with块期间引发的任何异常)。

答案 2 :(得分:5)

尽管使用上下文管理器的解决方案(由其他人提出)是最优雅的,并且也是我推荐的解决方案,但我想指出您的handle_exception函数可以更优雅地编写通过重新提出异常:

def handle_exception(e):
  try:
    raise e
  except CommonException1:
    Action_always_taken_for_CommonException1()
  except CommonException2:
    Action_always_taken_for_CommonException2()
  except Exception:
    Default_action_always_taken()