Skip to main content

Custom Exceptions in Python

Error Handling

Designing Custom Exceptions

Name your errors, add context, and keep your code understandable.

Base class

class BillingError(Exception):
"""Base exception for billing failures."""

class CardDeclined(BillingError):
pass
  • Inherit from Exception (or a more specific subclass).
  • Use a base class to catch related failures in one except BillingError.

Metadata

class CardDeclined(BillingError):
def __init__(self, *, user_id: str, reason: str):
self.user_id = user_id
super().__init__(f"Card declined: {reason}")

Expose helpful attributes for logging and analytics.

Catching custom exceptions

try:
process_payment(user_id)
except CardDeclined as exc:
logger.warning("Card declined for user %s: %s", exc.user_id, exc)
except BillingError:
logger.error("Billing failure")

Catch specific subclasses first, then broader base classes.

Next up in your learning path