deftest_finally():
try:
print(" In try")
return"from try"except:
print(" In except")
return"from except"finally:
print(" In finally (runs before return!)")
result = test_finally()
print(f"Got: {result}")
print()
# finally can override the return value (but don't do this!)defbad_practice():
try:
return1finally:
return2# overrides the return from try!print(f"bad_practice() = {bad_practice()}")
Output
Click "Run" to execute your code
finally runs even when the try block returns. If finally also has a return, it overrides the try's return — avoid this anti-pattern.
Challenge
Try modifying the code above to explore different behaviors. Can you extend the example to handle a new use case?