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.

Next up in your learning path