处理多个异常时共享Python代码

use*_*535 9 python exception-handling exception

我编写了一个程序,需要处理一个可以抛出多个异常的函数.对于我捕获的每个异常,我都有一些代码可以专门处理它.

但是,无论遇到哪个异常,我还有一些我想要运行的代码.我当前的解决方案是handle_exception()从每个except块调用的函数.

try:
    throw_multiple_exceptions()
except FirstException as excep:
    handle_first_exception()
    handle_exception()
except SecondException as excep:
    handle_second_exception()
    handle_exception()
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?我希望代码看起来像这样:

try:
    throw_multiple_exceptions()
except FirstException as excep:
    handle_first_exception()
except SecondException as excep:
    handle_second_exception()
except Exception as excep:
    handle_exception()
Run Code Online (Sandbox Code Playgroud)

rbp*_*rbp 8

PEP 0443怎么样?它非常棒,而且非常可扩展,因为您只需要编写代码并注册新的处理程序

from functools import singledispatch
@singledispatch
def handle_specific_exception(e): # got an exception we don't handle
    pass       

@handle_specific_exception.register(Exception1)
def _(e):
    # handle exception 1

@handle_specific_exception.register(Exception2)
def _(e):
    # handle exception 2

try:
    throw_multiple_exceptions()
except Exception as e:
    handle_specific_exception(e)
    handle_exception()
Run Code Online (Sandbox Code Playgroud)

  • OP没有说哪个版本的Python,所以值得一提的是这个功能是在Python 3.4中引入的,并且有一个[backport](https://pypi.python.org/pypi/singledispatch)可用于2.6到3.3. (3认同)

jon*_*rpe 6

您可以执行以下操作:

try:
    throw_multiple_exceptions()
except FirstException, SecondException as excep:
    if isinstance(excep, FirstException):
        handle_first_exception()
    else:
        handle_second_exception()
    handle_exception()
Run Code Online (Sandbox Code Playgroud)

  • 如果有很多不同的例外情况,看起来会很糟糕吗? (4认同)