Python Practice Question 9: Try Else Finally Order
Python · Test 1 · question 9 of 10
A function f() has four clauses: a try: block that runs print('T'), an except ValueError: block that runs print('E'), an else: block that runs print('L') and then return 'R', and a finally: block that runs print('F'). The script then calls print(f()).
Which lines are printed, and in what order?
Show answer and explanation
Answer:
The try block prints T and raises nothing, so except ValueError is skipped. The else clause runs when control leaves the try suite without an exception (and without a return, break or continue in the try suite itself), so it prints L. It then executes return 'R'. A finally clause always runs on the way out of a try statement, including when leaving through a return. So the return value 'R' is set aside, finally prints F, and only then does f() actually return 'R' to the caller, whose print outputs R last.
Option B treats the caller's print(f()) as if it could run before f() finishes. The outer print receives its argument only after f() has returned, and finally runs before that.
Option C is the classic misconception: a return never skips finally. That guarantee is what makes finally safe for cleanup such as closing files or releasing locks.
Option D runs finally before else. The order is always try, then except or else, then finally, and exceptions raised inside else are not caught by that statement's except clauses.
Reference: Compound statements: The try statement