What does this function return when both try and finally have a return statement?
It returns the value from the finally block. finally always runs last, and a return inside it overrides the earlier return and even discards a pending exception. This is why returning from finally is considered bad practice.
Explain it simply
You hand a letter to a courier at the door (the return in try). Before he leaves, the security guard (finally) takes it and gives him a different letter. The courier delivers whatever the guard gave him last.
Example
def f():
try:
return "try"
finally:
return "finally"
print(f()) # Output: finally
def g():
try:
raise ValueError("boom")
finally:
return "swallowed"
print(g()) # Output: swallowed
def h():
x = 1
try:
return x
finally:
x = 2
print(h()) # Output: 1In h, the return value 1 is already fixed when return x runs. Changing x in finally is too late to alter it.
What to say in the interview
"finally always executes before the function really returns. If finally itself contains a return, that value wins and any exception in flight is silently dropped. I never return or break inside finally; I use it only for cleanup."
Common mistakes
- Assuming a
returnintryends the function immediately, skippingfinally.