Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 06 / Topic 5 of 10

else and finally

  • else runs only if no exception happened in try.
  • finally runs 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: finally runs even when try hits return or an error that no except catches. Never return from inside finally: 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.

Search the guide