What is the execution order of `try`, `except`, `else` and `finally`, and what is the `else` clause specifically for?
Answer
Python runs the `try` block first; if an exception occurs, control jumps to the first matching `except` block, and if no exception occurs, the optional `else` block runs immediately after the `try` block completes cleanly. `finally` always runs last, whether or not an exception occurred and whether or not it was handled, making it the right place for guaranteed cleanup. The `else` block exists to separate "code that might raise the exception we're catching" from "code that should only run if it did not," avoiding accidentally catching exceptions raised by that follow-up code inside the `try` block itself.
Strong answer includes
- try runs, then except on error or else on success, finally always runs last
- finally is guaranteed cleanup regardless of outcome
- else separates protected code from follow-up code that should not be caught
Practical example
Run the code to see the result.
except handles only failures from the protected parse. else runs only after a successful try, while finally runs on both paths and is appropriate for guaranteed cleanup.
Expected result: For '4': 25 then cleanup. For 'bad': invalid then cleanup.