Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
Python interview question
Errors & context managersJuniorVery commonPractical

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

Keep follow-up work out of the protected try block
Python
editable · browser sandbox
Result
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.

#exceptions#control-flow

Sources

Errors and ExceptionsPython Software Foundation · try/except/else/finally control flow and exception chaining