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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With