问题描述
我编写了一个程序,该程序需要处理可能引发多个异常的函数.对于每个捕获到的异常,我都有一些专门处理它的代码.
I've written a program that needs to deal with a function that can throw multiple exceptions. For each exception I catch I have some code that will handle it specifically.
但是,无论捕获到哪个异常,我也都有一些我想运行的代码.我当前的解决方案是一个handle_exception()
函数,该函数从每个except
块中调用.
However, I also have some code I want to run no matter which exception was caught. My current solution is a handle_exception()
function which is called from each except
block.
try:
throw_multiple_exceptions()
except FirstException as excep:
handle_first_exception()
handle_exception()
except SecondException as excep:
handle_second_exception()
handle_exception()
是否有更好的方法可以做到这一点?我希望代码看起来像这样:
Is there a better way to do this?I would like the code to look like this:
try:
throw_multiple_exceptions()
except FirstException as excep:
handle_first_exception()
except SecondException as excep:
handle_second_exception()
except Exception as excep:
handle_exception()
推荐答案
PEP 0443 ?它非常棒且具有很好的可扩展性,因为您要做的就是编写代码并注册新的处理程序
how about PEP 0443? its awesome, and very scalable because all you have to do is code and register new handlers
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()
这篇关于处理多个异常时共享Python代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!