Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 844
Matthew Moisen Avatar asked Mar 13 '23 13:03

Matthew Moisen


1 Answers

You could add another level of try nesting:

try:
    try:
        raise KeyError()
    except KeyError:
        print "Caught KeyError"
        raise Exception()
except Exception:
    print "Caught Exception"
like image 63
ecatmur Avatar answered Mar 15 '23 23:03

ecatmur