Part 06 / Topic 5 of 10
else and finally
elseruns only if no exception happened intry.finallyruns always, error or not. Use it for clean-up (closing, logging).
Real-world example: an ATM that always prints "Thank you" at the end.
def withdraw(balance, text):
try:
amount = int(text)
except ValueError:
print("Invalid amount")
else:
print(f"Dispensing ₹{amount:,}. Left: ₹{balance - amount:,}")
finally:
print("Thank you for banking with us")
withdraw(5000, "2000")
withdraw(5000, "abc")
Dispensing ₹2,000. Left: ₹3,000
Thank you for banking with us
Invalid amount
Thank you for banking with us
| Block | Runs when |
|---|---|
try |
Always (first) |
except |
An exception matched |
else |
No exception happened |
finally |
Always (last) |
Full program: examples/04_else_finally_sales_report.py.
🔍 Going deeper:
finallyruns even whentryhitsreturnor an error that noexceptcatches. Neverreturnfrom insidefinally: it silently throws away the error (newer Python versions warn about this).
Done here? The practice set for Part 6 — 7 exercises with solutions — is on the part page.