Python · Module 6 · Lesson 21 min read

Custom Exceptions

Why make your own?

A named error like InsufficientFundsError explains the problem far better than a generic Exception, and callers can catch exactly that case.

How

Subclass Exception (never BaseException):

Python
class AppError(Exception):
    """Base class for this app's errors."""

class InsufficientFundsError(AppError):
    def __init__(self, balance, amount):
        super().__init__(f"Need {amount}, only have {balance}")
        self.balance = balance
        self.amount = amount
  • A shared base class (AppError) lets callers catch all of your app's errors at once.
  • Store useful data as attributes so the handler can use it.

Exception chaining

raise ConfigError("bad config") from err keeps the original error in the traceback, which helps a lot when debugging.

▶️ Runs in the app.

Example

Python
class AppError(Exception):
    """Base class for all errors in this app."""

class InsufficientFundsError(AppError):
    def __init__(self, balance, amount):
        super().__init__(f"Need {amount}, but balance is only {balance}")
        self.shortfall = amount - balance

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(balance, amount)
    return balance - amount

try:
    withdraw(50, 120)
except InsufficientFundsError as e:
    print(e)                       # Need 120, but balance is only 50
    print("Short by", e.shortfall) # Short by 70

# Chaining keeps the original cause
try:
    try:
        int("abc")
    except ValueError as err:
        raise AppError("Could not read the amount") from err
except AppError as e:
    print(e, "| caused by:", repr(e.__cause__))