Home › Output practice › finally runs before the return lands
Predict the output: finally runs before the return lands
🔮 Predict the outputTopic: exceptionsDifficulty: hardNo login needed
The snippet
The return "try" looks like the last word. It is not: the value is prepared, then finally executes, and only then does the function hand the value back. So the order of printed lines surprises almost everyone.
def pick():
try:
return "try"
finally:
print("finally")
print(pick())
Your prediction
Type exactly what this program prints — one line per print() call:
The output
finally
try
Verified against CPython 3.11 in this repo's build
Line-by-line explanation
print(pick())
The call starts and enters thetrybody.return "try"
Python computes the return value ("try") and *pauses* — the value is held while the mandatory cleanup runs.print("finally")finallyalways runs, return or not → printsfinallyfirst.(then the return completes)
Now"try"reachesprint→try. Whole output:finallynewlinetry.what would change it
Areturn(or raise) *inside*finallyreplaces the pending value — another common exam twist, and a real bug source.
The rule you can reuse
finally runs on every exit path: normal end, return, or an uncaught exception. Use it for closing files and releasing resources; never return from it.
Why most predictions break here
Answering try then finally. That would need the return to escape immediately, which is exactly what finally exists to prevent.
Quick fire
Same rule, two more shapes. Predict first, then open.
Predict this too
def f():
try:
1 / 0
except ZeroDivisionError:
return "caught"
finally:
print("clean")
print(f())Outputclean
caught
The handler's return still waits for cleanup → clean then caught.
Predict this too
def f():
try:
return "a"
finally:
return "b"
print(f())Outputb
Returning inside finally overrides the pending value → b, and the exception path swallows errors too.
Share your result
Challenge a friend — the link contains the question, never the answer:
Copied ✓Keep practising this rule
More output questions → All interactive problemsQuestions this page answers
What about `else` in try/except?
else runs only when no exception was raised, and it runs before finally. Order: try → (except if raised, else if not) → finally.
Is with the same thing?
Conceptually yes — with open(path) as fh calls fh.close() on every exit path, which is why style guides prefer it over hand-written try/finally.