Subclass Exception (never BaseException) to define a custom error type (class ValidationError(Exception): pass), optionally override __init__ to attach structured context attributes while passing a clear message to super().__init__(message), and raise it with raise ValidationError(...)—using raise NewError(...) from err when wrapping an underlying exception to preserve the original traceback chain.
Basic Example
# 1. Recommended (minimal custom exception — inherits full Exception behavior):
class InsufficientFundsError(Exception):
"""Raised when an account balance cannot cover a withdrawal."""
# 2. Custom exception with structured attributes + default formatted message:
class PaymentGatewayError(Exception):
def __init__(self, message: str, *, status_code: int, transaction_id: str) -> None:
super().__init__(f"[{status_code}] {message} (tx={transaction_id})")
self.status_code = status_code
self.transaction_id = transaction_id
def withdraw(balance: float, amount: float) -> float:
if amount > balance:
raise InsufficientFundsError(f"Cannot withdraw ${amount:.2f} from ${balance:.2f}")
return balance - amount
try:
withdraw(50.0, 120.0)
except InsufficientFundsError as err:
print(f"Handled domain error: {err}")
# Output: Handled domain error: Cannot withdraw $120.00 from $50.00
Key Details & Edge Cases
- Always inherit from
Exception, NEVER fromBaseException:BaseExceptionis the parent of system-exiting signals (KeyboardInterrupt,SystemExit,GeneratorExit). SubclassingBaseExceptionprevents callers catchingexcept Exception:from intercepting your error and mixes domain failures with interpreter termination signals.
- Create a module/package base exception hierarchy (
class AppError(Exception)):- Define a root base class for your library or service (e.g.,
class BillingError(Exception): pass) and inherit specific errors from it (class CardDeclinedError(BillingError): pass). Callers can then catch either granular errors (except CardDeclinedError:) or any error from your module (except BillingError:).
- Define a root base class for your library or service (e.g.,
- Always call
super().__init__(message)and keep custom__init__arguments pickle-safe:- Passing the human-readable message to
super().__init__(message)populateserr.argssostr(err), logging, and tracebacks display cleanly. - If your exception crosses
multiprocessingprocess boundaries orpickle, ensureself.argscontains all positional arguments passed to__init__(super().__init__(message, status_code, transaction_id)), otherwise unpickling raisesTypeError: __init__() missing required positional arguments.
- Passing the human-readable message to
- Chain underlying exceptions with
raise ... from err(or suppress withfrom None):- When translating a low-level error (like
KeyErrororrequests.HTTPError) into your domain exception, useraise ConfigLoadError("Missing API key") from errso Python preserves the root-cause traceback (The above exception was the direct cause...). Usefrom Noneonly when intentionally hiding noisy internal implementation details.
- When translating a low-level error (like
- Follow PEP 8 naming (
Errorsuffix,CapWords):- Name exceptions ending in
Error(e.g.,InvalidTokenError,QuotaExceededError) rather thanException, reservingWarningsubclasses (UserWarning,DeprecationWarning) for non-fatalwarnings.warn()alerts.
- Name exceptions ending in
Comparison of Custom Exception Design Patterns in Python 3
| Pattern | Inheritance | Extra Metadata | Pickling / multiprocessing Safe? |
Best Used When |
|---|---|---|---|---|
class MyError(Exception): pass (Default) |
Exception |
String message via str(err) / err.args[0] |
Yes (out of the box) | Simple domain errors where the exception class name + message already convey full context. |
| Base + Subclass Hierarchy | class PkgError(Exception) $\rightarrow$ class SubError(PkgError) |
Inherited | Yes | Libraries, APIs, or services needing both granular and catch-all error handling. |
Structured Attributes (__init__ + super().__init__) |
Exception (or PkgError) |
Typed fields (err.code, err.field) |
Yes (if all required args go to super().__init__) |
API/validation errors where callers inspect machine-readable codes or retry metadata. |
| Multiple Inheritance with Built-ins | class InvalidAgeError(ValueError, PkgError) |
Standard ValueError + domain base |
Yes | Allowing callers to catch either standard ValueError or your custom PkgError. |
You must log in or register to comment.
