简体   繁体   中英

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. 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. Do I just have to add that code to each except block?

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. After the whole try/except , add if execute_code: , then implement the code to execute if an exception occurred once inside the if block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM