Part 06 / Topic 7 of 10
Custom exceptions
Make your own exception with a small class that inherits from Exception (it becomes a special kind of Exception). The name tells the reader exactly what went wrong. Exception names end with Error.
(Classes are covered properly in Stage 2, Part 9. For now, copy this two-line pattern. The docstring is the whole body; you can also write pass.)
Real-world example: a bank account that refuses to go below zero.
class InsufficientBalanceError(Exception):
"""Raised when a withdrawal is more than the balance."""
def withdraw(balance, amount):
if amount > balance:
raise InsufficientBalanceError(f"Need ₹{amount:,}, have only ₹{balance:,}")
return balance - amount
try:
withdraw(1500, 4000)
except InsufficientBalanceError as e:
print("Declined:", e) # Declined: Need ₹4,000, have only ₹1,500
Full program: examples/03_bank_withdraw.py.
🔍 Going deeper: for a bigger program, make one base error (
class BankError(Exception)) and inherit the others from it (class InsufficientBalanceError(BankError)). Callers can then catch one type, or all of your errors withexcept BankError:. The example file does this.
Done here? The practice set for Part 6 — 7 exercises with solutions — is on the part page.