In what order do try, except, else and finally run?
Question
Predict exactly what this code prints, line by line.
Then add return -1 as the last line of the finally block. What do parse("42") and parse(None) return now?
def parse(text): try: value = int(text) except ValueError: print("except") return None else: print("else") return value finally: print("finally") print(parse("42")) print(parse("x"))
Show hints (3)
- "TWO PATHS"
Follow
parse("42")andparse("x")separately. On each path, which ofexceptandelseruns? Can both ever run? - "RETURN WAITS"
A
returninsidetry,exceptorelsedoesn't leave the function at once. Python keeps the value, runsfinally, and only then returns. - "THE LAST RETURN WINS"
A function returns the value of the last
returnthat runs, andfinallyalways runs last. What happens to the value that was waiting, or to an exception nobody caught?
Show checked explanation
try runs first. Then except runs if a matching exception was raised, or else if nothing was raised. finally runs last in every case, even when a block before it returns. So the code prints else, finally, 42, except, finally, None. With return -1 in finally, both calls return -1, and the TypeError from parse(None) is lost.
def parse(text): try: value = int(text) # 1. always runs first except ValueError: print("except") # 2a. only if int() raised ValueError return None else: print("else") # 2b. only if nothing was raised return value finally: print("finally") # 3. always runs last, even after return print(parse("42")) print(parse("x"))
else finally 42 except finally None
Code run on CPython 3.12 against the examples above. Checked by an editor other than the author.
Walkthrough
Here is each call, step by step:
| call | try | except | else | finally | returns |
|---|---|---|---|---|---|
parse("42") | int works | skipped | prints else | prints finally | 42 |
parse("x") | ValueError | prints except | skipped | prints finally | None |
except and else never both run. else runs only when the try block raised nothing.
The tricky part is return. When Python reaches return value in else, it doesn't leave right away. It keeps the value 42, runs finally, and only then returns. That's why finally is printed before 42: the caller prints the result only after the function has finished.
Now add return -1 at the end of finally:
finally:
print("finally")
return -1The function returns the value of the last return that runs, and finally always runs last. So parse("42") returns -1, not 42.
parse(None) is worse. int(None) raises TypeError, which except ValueError doesn't catch. finally runs, prints finally, and its return throws the TypeError away. The caller gets -1 and never sees the error.
Python 3.12 runs this code with no warning. Python 3.14 shows a SyntaxWarning when it compiles a return, break or continue that leaves a finally block (PEP 765).
Common mistakes
- Putting more code in
trythan the line that can fail. AValueErrorfrom that extra code is then caught and reported as bad input. Move code that should run only on success toelse. - Using
return,breakorcontinueto jump out offinally. It cancels whatever was pending: the real return value is lost, and any exception disappears silently, evenKeyboardInterrupt. - Silencing errors with a bare
except:orexcept Exception: pass. Both hide real bugs, such as a typo that raisesNameError. A bareexcepteven catchesKeyboardInterruptandSystemExit.
Follow-up questions
- "How do you raise your own error but keep the original one?" Write
raise ConfigError("bad port") from errinside theexceptblock. The new exception stores the original in__cause__. The traceback shows both, joined by "The above exception was the direct cause of the following exception".raise ... from Nonehides the original on purpose. - "Does
finallyalways run?" Almost always. It runs on every way out oftry:return,break,continue, or any exception, includingKeyboardInterruptand theSystemExitraised bysys.exit(). It does not run afteros._exit(), which ends the process at once, or when the process is killed from outside. - "When would you use
withinstead offinally?" Whenever the resource supports it: files, locks, database connections.with open(path) as f:closes the file on every way out of the block, like afinally, in one line. Keepfinallyfor cleanup that has no context manager.
What a strong answer covers
Gets the exact print order right and explains that return waits for finally. Says why else keeps the try block small, and warns that return in finally hides exceptions, which Python 3.14 flags with a SyntaxWarning.
Open in interactive practice deck →