How do you define and raise custom exception classes in Python 3? | A1Lab@MZeeshanM to PythonEnglish • 3 days ago

How do you define and raise custom exception classes in Python 3?

message-square
0

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 from BaseException:
    • BaseException is the parent of system-exiting signals (KeyboardInterrupt, SystemExit, GeneratorExit). Subclassing BaseException prevents callers catching except 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:).
  • Always call super().__init__(message) and keep custom __init__ arguments pickle-safe:
    • Passing the human-readable message to super().__init__(message) populates err.args so str(err), logging, and tracebacks display cleanly.
    • If your exception crosses multiprocessing process boundaries or pickle, ensure self.args contains all positional arguments passed to __init__ (super().__init__(message, status_code, transaction_id)), otherwise unpickling raises TypeError: __init__() missing required positional arguments.
  • Chain underlying exceptions with raise ... from err (or suppress with from None):
    • When translating a low-level error (like KeyError or requests.HTTPError) into your domain exception, use raise ConfigLoadError("Missing API key") from err so Python preserves the root-cause traceback (The above exception was the direct cause...). Use from None only when intentionally hiding noisy internal implementation details.
  • Follow PEP 8 naming (Error suffix, CapWords):
    • Name exceptions ending in Error (e.g., InvalidTokenError, QuotaExceededError) rather than Exception, reserving Warning subclasses (UserWarning, DeprecationWarning) for non-fatal warnings.warn() alerts.

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.