3Ge*_*Gee 4 python exception-handling exception try-except
我有这样的代码:
try:
return make_success_result()
except FirstException:
handle_first_exception()
return make_error_result()
except SecondException:
handle_second_exception()
return make_error_result()
Run Code Online (Sandbox Code Playgroud)
我想知道有什么办法可以实现这个目标:
try:
# do something
except Error1:
# do Error1 specific handling
except Error2:
# do Error2 specific handling
else:
# do this if there was no exception
????:
# ALSO do this if there was ANY of the listed exceptions (e.g. some common error handling)
Run Code Online (Sandbox Code Playgroud)
因此代码以下列顺序之一执行:
try > else > finally
try > except > ???? > finally
Run Code Online (Sandbox Code Playgroud)
编辑:我的观点是
????块应该在任何except块之后执行,这意味着它是错误处理的补充,而不是替换.
在这种情况下我要做的是在你得到异常时设置一个布尔值,如下所示:
got_exception = False
try:
# do something
except Error1:
# do Error1 specific handling
got_exception = True
except Error2:
# do Error2 specific handling
got_exception = True
else:
# If there was no exception
finally:
if got_exception:
# ALSO do this if there was ANY exception (e.g. some common error handling)
Run Code Online (Sandbox Code Playgroud)
这应该符合您的需求,这是IMO最简单的方法,将所有已呈现的解决方案组合到最易于调试的最易读的代码结构中.
| 归档时间: |
|
| 查看次数: |
190 次 |
| 最近记录: |