An exception is an error that happens while the program runs. Unhandled, it stops the program with a traceback.
Common exceptions
ValueError, TypeError, ZeroDivisionError, KeyError, IndexError, FileNotFoundError, AttributeError, ImportError.
try / except
try:
risky code
except ValueError:
handle it
except (KeyError, IndexError) as e:
print(e)
else:
runs if no error
finally:
always runs (cleanup)
Catch specific exceptions. A bare except: hides real bugs.
raise
raise ValueError("Age cannot be negative") — signal a problem yourself. Inside except, a bare raise re-raises the same error.
Custom exceptions
class InsufficientBalance(Exception): pass — clear names for your app's errors.
Exception chaining
raise PaymentError("Payment failed") from err keeps the original cause.
Use logging.exception() inside except to log the full traceback.
Example
class InsufficientBalance(Exception):
pass
def withdraw(balance, amount):
if amount <= 0:
raise ValueError("Amount must be positive")
if amount > balance:
raise InsufficientBalance(f"Balance {balance} is less than {amount}")
return balance - amount
for attempt in ["abc", "-50", "5000", "300"]:
try:
amount = int(attempt)
balance = withdraw(1000, amount)
except ValueError as e:
print(f"{attempt!r}: invalid -> {e}")
except InsufficientBalance as e:
print(f"{attempt!r}: {e}")
else:
print(f"{attempt!r}: success, new balance {balance}")
finally:
print(" (transaction checked)")
'abc' gives an invalid literal error, '-50' gives Amount must be positive, '5000' gives Balance 1000 is less than 5000, and '300' succeeds with new balance 700. finally prints after every attempt.