[英]try-except block: analogue for 'else' if exception was raised
我有这样的代码:
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
编辑:我的观点是
????
块应该在任何一个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)
这应该符合您的需求,这是IMO最简单的方法,将所有已呈现的解决方案组合到最易于调试的最易读的代码结构中。
你可以做:
try:
# Do something
except Error1:
# Do Error1 specific handling
except Error2:
# Do Error2 specific handling
except Exception:
# Handle any other exception (Generic exception handling)
else:
# Do this if there were no exceptions
finally:
# Execute this regardless
你实际上可以这样做:
try:
print 'try'
# 1/0
# {}[1]
# {}.a
except AttributeError, KeyError: # only handle these exceptions..
try:
raise # re-raise the exception so we can add a finally-clause executing iff there was an exception.
except AttributeError:
print 'attrerr'
# raise ... # any raises here will also execute 'common'
except KeyError:
print 'keyerror'
finally: # update 0: you wanted the common code after the exceptions..
print "common"
else:
print 'no exception'
但它是可怕的,我不建议你没有大量的评论描述为什么..
更新:除了内部try-block中的有趣异常之外,您不需要捕获任何内容。 代码已更新。
UPDATE2:根据OP的说明,当抛出一个有趣的异常时,应该执行common
。 代码已更新。 @MatTaylor的版本绝对是要走的路;-)
是的,python中的异常处理包括else
和finally
子句。 你可以这样做:
try:
# do something
except Error1:
# do Error1 specific handling
except Error2:
# do Error2 specific handling
else:
# do this if there was no exception
finally:
# Do this in any case!
python文档提到了这些块,即使它没有显示您需要的完整示例。
编辑:我看到你没有专门要求清理一般情况。 Python文档就是这样说的:
try语句有另一个可选子句,用于定义必须在所有情况下执行的清理操作。
请注意, finally
将运行是否存在异常。 结合else
块,你仍然可以做你想要的。
您可以捕获所有错误并在错误处理代码中检查其类型,如下所示:
try:
# do something
except Exception as e:
if isinstance(e, Error1):
# do Error1 specific handling
elif isinstance(e, Error2):
# do Error2 specific handling
else:
# do non-Error1/Error2 handling
# ALSO do this if there was ANY exception (e.g. some common error handling)
else:
# do this if there was no exception
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.