6
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?

4
  • 2
    Yes. Put the code you're using to handle Exception in a function. Then call that function in both places. Commented Apr 20, 2016 at 21:13
  • except clauses only catch errors thrown in the try; otherwise, you couldn't re-raise if you wanted to. Commented Apr 20, 2016 at 21:14
  • 1
    hmmm, can you explain what you are trying to achieve? the standard approach to re-raising a caught exception that you've decided not to handle after all is raise, without anything else. That may or may not fit your reqs in this case. Can't tell from your code alone. Commented Apr 20, 2016 at 21:20
  • 1
    I'll give even stronger suggestion than @JLPeyret: Do not use exceptions for flow control. What are you actually trying to achieve? There might be more elegant solution. Commented Apr 20, 2016 at 22:34

1 Answer 1

9

You could add another level of try nesting:

try:
    try:
        raise KeyError()
    except KeyError:
        print "Caught KeyError"
        raise Exception()
except Exception:
    print "Caught Exception"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.