Skip to main content
Albero Academy

Custom Exceptions

Define your own exception types for clear, catchable errors.

Exceptions8 min

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

a custom exception
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 - amount
try:
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):

a small hierarchy
class BankError(Exception): ...
class InsufficientFundsError(BankError): ...
class AccountFrozenError(BankError): ...
try:
do_transaction()
except BankError as e: # catches BOTH subclasses
log(e)

Key takeaways

  1. 01Subclass Exception to create custom, domain-specific error types.
  2. 02raise triggers an exception; include a helpful message.
  3. 03A base exception with subclasses lets callers catch broadly or narrowly.
  4. 04Custom exceptions make error handling specific, readable and self-documenting.
  5. 05Catch them by type with except MyError as e.

Finished this chapter?

Mark it complete to track your progress through Python.