What does this print?
def f():
try:
return 1
finally:
return 2
print(f())Options
- 1
- 2 (Correct option)
- 1 then 2
- SyntaxError
Answer
2
Why
finally always runs, even after a return in try.
If finally also contains a return, that second return replaces the first one, so f() returns 2. It can even hide exceptions.
That is why a return inside finally is considered a bug; recent Python versions warn about it.
Remember
Never return inside finally.