[英]Is there a way in python to execute a piece of code only if any exception is raised in a try/except block?
I have a try/except
block with multiple except blocks.我有一个带有多个 except 块的
try/except
except 块。 I want to be able to execute a piece of code only if any of the exceptions are raised.我希望只有在引发任何异常时才能执行一段代码。 Kind of like the
finally
statement, but finally
execute regardless of if an exception was raised or not.有点像
finally
语句,但无论是否引发异常, finally
执行。 Do I just have to add that code to each except
block?我是否只需将该代码添加到每个
except
块中?
You can do your own type checking in the exception handler to deal with type-specific and general code.您可以在异常处理程序中进行自己的类型检查,以处理特定于类型的代码和通用代码。
def it_will_end_in_tears():
raise ValueError("bad value")
try:
val = it_will_end_in_tears()
except (TypeError, ValueError) as e:
if isinstance(e, TypeError):
print("type error stuff")
elif isinstance(e, ValueError):
print("value error stuff")
print("common stuff")
finally:
print("finally")
Instead of copy+pasting the code into each except block, i would declare a boolean execute_code = False
and set it to True
in each of the except blocks.我不会将代码复制+粘贴到每个 except 块中,而是声明一个布尔值
execute_code = False
并将其在每个 except 块中设置为True
。 After the whole try/except
, add if execute_code:
, then implement the code to execute if an exception occurred once inside the if
block.在整个
try/except
,添加if execute_code:
,然后在if
块内实现一次发生异常时执行的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.