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)
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)
您可以执行以下操作:
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)
| 归档时间: |
|
| 查看次数: |
1615 次 |
| 最近记录: |