简体   繁体   中英

Python Try/Except with multiple except blocks

try:
    raise KeyError()
except KeyError:
    print "Caught KeyError"
    raise Exception()
except Exception:
    print "Caught Exception"

As expected, raising Exception() on the 5th line isn't caught in the final except Exception clause. In order the catch the exception inside of the except KeyError block, I have to add another try...except like this and duplicate the final except Exception logic:

try:
    raise KeyError()
except KeyError:
    print "Caught KeyError"
    try:
        raise Exception()
    except Exception:
        print "Caught Exception"
except Exception:
    print "Caught Exception"

In Python, is it possible to pass the flow of execution to the final except Exception block like I am trying to do? If not, are there strategies for reducing the duplication of logic?

You could add another level of try nesting:

try:
    try:
        raise KeyError()
    except KeyError:
        print "Caught KeyError"
        raise Exception()
except Exception:
    print "Caught Exception"

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