gpt4 book ai didi

python - try-except block : analogue for 'else' if exception was raised

转载 作者:太空狗 更新时间:2023-10-30 02:09:49 25 4
gpt4 key购买 nike

我有这样的代码:

try:
return make_success_result()
except FirstException:
handle_first_exception()
return make_error_result()
except SecondException:
handle_second_exception()
return make_error_result()

我想知道有什么办法可以做到这一点:

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)

因此代码按以下顺序之一执行:

try > else > finally
try > except > ???? > finally

EDIT: my point here is that ???? block should execute right after ANY of the except blocks, meaning that it's an addition to error handling, not a substitution.

最佳答案

在这种情况下,我会做的是在出现异常时设置一个 bool 值,如下所示:

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)

这应该符合您的需求,这是 IMO 将所有已呈现的解决方案组合成最易调试的最易读代码结构的最简洁方法。

关于python - try-except block : analogue for 'else' if exception was raised,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33646842/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com