简体   繁体   English

只有当在 try/except 块中引发任何异常时,python 中有没有办法执行一段代码?

[英]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.

相关问题 在python中,有没有办法在满足条件时进入try/except块,否则直接执行try块中的代码? - In python, is there a way to enter a try/except block if a condition is met, otherwise execute the code in the try block plainly? try-except 块:如果引发异常,则类似于“else” - try-except block: analogue for 'else' if exception was raised try和except均引发异常。 - Exception raised in both try and except . 要在Python的try语句中检查的if语句,还需要执行代码以防引发异常 - An if statement to check within try statement in Python, need the code to execute in case an exception is raised as well 如何检测是否从python中的try块引发了异常? - How to detect if an exception has been raised from a try block in python? 在 Python Try/Except 块中测试代码 - Testing a code in Python Try/Except Block 如何将try和except合并到python中的代码块中 - how to incorporate try and except into a block of code in python 将try块与try代码合并在一起 - Incorporate try except block with python code try代码块中的Python代码崩溃 - Python code crashes within try except block 比较时,为什么在 try/except 块中引发的异常不等于方法中的 HTTPError? - Why is raised Exception in a try/except block not equal to HTTPError in a method when compared?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM