Beyond Python's built-in exceptions, you can define your own by subclassing Exception. Domain-specific error types make your code self-documenting and let callers catch exactly the failure they care about, rather than a generic ValueError.
Defining & raising
class InsufficientFundsError(Exception):"""Raised when a withdrawal exceeds the balance."""def withdraw(balance, amount):if amount > balance:raise InsufficientFundsError(f"Need {amount}, have {balance}")return balance - amounttry:withdraw(100, 500)except InsufficientFundsError as e:print("Blocked:", e) # Blocked: Need 500, have 100
Exception hierarchies
For a larger app, define a base exception and subclass it, so callers can catch broadly (the base) or narrowly (a specific subclass):
class BankError(Exception): ...class InsufficientFundsError(BankError): ...class AccountFrozenError(BankError): ...try:do_transaction()except BankError as e: # catches BOTH subclasseslog(e)
Key takeaways
- 01Subclass Exception to create custom, domain-specific error types.
- 02raise triggers an exception; include a helpful message.
- 03A base exception with subclasses lets callers catch broadly or narrowly.
- 04Custom exceptions make error handling specific, readable and self-documenting.
- 05Catch them by type with except MyError as e.
