Tutorials Python Python Custom Exceptions
Ch 42 / 58
Python Intermediate 12 min read Chapter 42 of 58

Python Custom Exceptions

Built-in exceptions like ValueError and TypeError are generic. Real applications need domain-specific errors that communicate exactly what went wrong — InsufficientFundsError, UserNotFoundError, InvalidEmailError. Custom exception classes let you build a rich error model for your module, carry extra context (not just a message), build hierarchies that callers can catch at the right level of specificity, and produce error messages that immediately guide developers to the fix.

What you'll learn in this chapter
Minimal custom exception — just subclassing
Adding extra attributes and custom __init__
Building exception hierarchies for a module
Custom __str__ and __repr__ for better messages
Domain-driven exception design patterns
Exception groups (Python 3.11+) — ExceptionGroup
Advertisement

Minimal Custom Exception — Just Subclassing

The simplest custom exception is just a class that inherits from Exception (or a more specific built-in). Even with a bare pass body, it gives you a named, catchable exception type that instantly communicates domain intent.

Building a custom exception — 4 levels of detail
Level 1 Minimal — just a name
Enough to catch specifically. Zero extra code needed.
class AppError(Exception): pass
Level 2 Custom message via __init__
Pass a formatted message to super().__init__(). Still one exception object.
def __init__(self, name): super().__init__(f"User '{name}' not found")
Level 3 Extra attributes for context
Add domain-specific attributes so callers can extract structured info programmatically.
self.user_id = user_id # caller can inspect e.user_id
Level 4 Custom __str__ / __repr__
Override for developer-friendly debug output and log messages.
def __repr__(self): return f"NotFoundError(id={self.user_id!r})"
Python — minimal_custom_exception.py
# ── Level 1: minimal — just a name ───────────────────
class DatabaseError(Exception): pass
class NetworkError(Exception):  pass
class ParseError(Exception):    pass

# Callers can now catch specifically
try:
    raise DatabaseError("connection refused")
except DatabaseError as e:
    print(f"DB error: {e}")           # DB error: connection refused
except NetworkError:
    print("Network issue")

# Custom exceptions ARE still Exception instances
print(issubclass(DatabaseError, Exception))   # True
print(isinstance(DatabaseError(), Exception)) # True

# ── Inherit from a more specific built-in ─────────────
class InvalidConfigError(ValueError):
    """Config value is invalid — inherits from ValueError."""
    pass

try:
    raise InvalidConfigError("port must be 1-65535")
except InvalidConfigError:
    print("Custom handler")
# Also catchable as ValueError:
try:
    raise InvalidConfigError("bad port")
except ValueError:
    print("Caught as ValueError too")

Extra Attributes — Structured Exception Context

Custom exceptions become truly powerful when they carry extra attributes beyond a message string. These let callers extract structured information programmatically — without parsing error strings — to log context, display field-level errors, or make decisions based on error type.

Python — exception_with_attributes.py
# ── ValidationError with field and code ──────────────
class ValidationError(Exception):
    """Raised when input validation fails."""

    def __init__(self, field: str, message: str, code: str = "invalid"):
        self.field   = field
        self.message = message
        self.code    = code
        super().__init__(f"[{code}] {field}: {message}")

# ── HTTPError with status code ────────────────────────
class HTTPError(Exception):
    """Raised for HTTP-level errors."""

    def __init__(self, status: int, url: str, detail: str = ""):
        self.status = status
        self.url    = url
        self.detail = detail
        super().__init__(f"HTTP {status} for {url}: {detail}")

# ── Usage — accessing attributes ──────────────────────
def validate_email(email):
    if "@" not in email:
        raise ValidationError(
            field="email",
            message="must contain @",
            code="INVALID_FORMAT"
        )
    return email.strip().lower()

try:
    validate_email("aliceatexample.com")
except ValidationError as e:
    print(str(e))             # [INVALID_FORMAT] email: must contain @
    print(e.field)            # email
    print(e.code)             # INVALID_FORMAT
    print(e.message)          # must contain @

# ── Multiple validation errors ────────────────────────
class MultiValidationError(Exception):
    """Carries a list of ValidationError instances."""

    def __init__(self, errors: list):
        self.errors = errors
        msgs = [str(e) for e in errors]
        super().__init__(f"{len(errors)} validation errors: {'; '.join(msgs)}")

    def __iter__(self):               # for e in exc: ...
        return iter(self.errors)

Custom __str__ and __repr__ for Better Messages

Override __str__ for a readable human-facing message and __repr__ for a developer-friendly debug representation. Well-crafted exception messages significantly reduce debugging time.

Python — exception_str_repr.py
class NotFoundError(Exception):
    """Resource not found exception."""

    def __init__(self, resource: str, identifier):
        self.resource   = resource
        self.identifier = identifier

    def __str__(self):
        # Human-readable: "User with id=42 was not found"
        return f"{self.resource} with id={self.identifier} was not found"

    def __repr__(self):
        # Developer debug: NotFoundError(resource='User', identifier=42)
        return (f"NotFoundError(resource={self.resource!r}, "
                f"identifier={self.identifier!r})")

err = NotFoundError("User", 42)
print(str(err))            # User with id=42 was not found
print(repr(err))           # NotFoundError(resource='User', identifier=42)

# How Python uses them:
try:
    raise NotFoundError("Product", "SKU-404")
except NotFoundError as e:
    print(f"Error: {e}")        # calls __str__
    print(f"Debug: {e!r}")      # calls __repr__
    print(e.resource)           # Product

# Good message checklist:
# ✅ "User with id=42 not found"  ← specific, actionable
# ❌ "error"                       ← useless
# ❌ "not found"                   ← what wasn't found?
# ✅ "Price must be > 0, got -5"  ← shows bad value
Advertisement
🐍
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Exception Hierarchies — Catching at the Right Level

A well-designed exception hierarchy lets callers choose how specific to be. Catch a specific subclass for targeted handling; catch the base class to handle all errors from your module. The pattern mirrors Python's own hierarchy where FileNotFoundError → OSError → Exception.

Sample app exception hierarchy — catch at any level
Exception
(Python built-in)
└─
AppError
← module base — catches everything below
├─
UserError
← catches all user-related errors
├─
UserNotFoundError
└─
UserPermissionError
├─
PaymentError
← catches all payment errors
├─
InsufficientFundsError
└─
CardDeclinedError
└─
DatabaseError
Python — exception_hierarchy.py
# ── Build the hierarchy ───────────────────────────────
class AppError(Exception):
    """Base for all errors raised by this application."""

class UserError(AppError):
    """Base for all user-related errors."""

class UserNotFoundError(UserError):
    def __init__(self, user_id):
        self.user_id = user_id
        super().__init__(f"User {user_id!r} not found")

class UserPermissionError(UserError):
    def __init__(self, user_id, action):
        self.user_id = user_id
        self.action  = action
        super().__init__(f"User {user_id!r} cannot {action!r}")

class PaymentError(AppError):
    """Base for all payment errors."""

class InsufficientFundsError(PaymentError):
    def __init__(self, balance, amount):
        self.balance = balance
        self.amount  = amount
        super().__init__(
            f"Insufficient funds: balance=₹{balance}, required=₹{amount}")

class CardDeclinedError(PaymentError):
    def __init__(self, reason="unknown"):
        self.reason = reason
        super().__init__(f"Card declined: {reason}")

# ── Three catching levels ─────────────────────────────
def process_payment(user_id, amount):
    try:
        do_charge(user_id, amount)
    except InsufficientFundsError as e:
        print(f"Top up needed: ₹{e.amount - e.balance} more")
    except PaymentError as e:       # catches CardDeclinedError too
        print(f"Payment issue: {e}")
    except AppError as e:           # catches UserError, DatabaseError...
        print(f"App error: {e}")

Domain-Driven Exception Design

In professional Python projects, exceptions are part of your domain model — they should reflect business concepts, not implementation details. Here's how to design exceptions for a complete service layer:

Python — domain_exceptions.py
# ── A complete exception module (exceptions.py) ───────
"""
Domain exceptions for the banking service.

Hierarchy:
  BankingError (base)
  ├── AccountError
  │   ├── AccountNotFoundError
  │   └── AccountFrozenError
  └── TransactionError
      ├── InsufficientFundsError
      └── DailyLimitExceededError
"""
from __future__ import annotations
from dataclasses import dataclass, field
from datetime import datetime


class BankingError(Exception):
    """All banking service errors stem from this."""
    def __init__(self, message: str, context: dict | None = None):
        super().__init__(message)
        self.context   = context or {}
        self.timestamp = datetime.now().isoformat()

    def to_dict(self) -> dict:
        return {
            "error":     type(self).__name__,
            "message":   str(self),
            "context":   self.context,
            "timestamp": self.timestamp,
        }


class AccountError(BankingError): pass
class TransactionError(BankingError): pass


class AccountNotFoundError(AccountError):
    def __init__(self, account_id: str):
        self.account_id = account_id
        super().__init__(
            f"Account '{account_id}' not found",
            context={"account_id": account_id}
        )


class InsufficientFundsError(TransactionError):
    def __init__(self, account_id: str, balance: float, required: float):
        self.account_id = account_id
        self.balance    = balance
        self.required   = required
        self.shortfall  = required - balance
        super().__init__(
            f"Insufficient funds in {account_id}: "
            f"balance=₹{balance:.2f}, required=₹{required:.2f}",
            context={"account_id": account_id, "balance": balance,
                     "required": required, "shortfall": self.shortfall}
        )


# ── Usage with to_dict() for API responses ────────────
def transfer(from_id, to_id, amount):
    try:
        do_transfer(from_id, to_id, amount)
    except BankingError as e:
        return {"success": False, **e.to_dict()}
    return {"success": True}

Exception Groups (Python 3.11+)

ExceptionGroup allows raising and handling multiple exceptions simultaneously — particularly useful in async/concurrent code where several operations may fail at once. Use except* to handle individual exception types from a group.

Python 3.11+ — exception_groups.py
# ── ExceptionGroup — raise multiple exceptions at once ──
def validate_form(data: dict) -> list:
    errors = []
    if not data.get("name"):
        errors.append(ValueError("name is required"))
    if "@" not in data.get("email", ""):
        errors.append(ValueError("email must contain @"))
    if data.get("age", 18) < 18:
        errors.append(TypeError("age must be >= 18"))
    if errors:
        raise ExceptionGroup("form validation failed", errors)
    return data

# ── except* — handle types from a group ──────────────
try:
    validate_form({"name": "", "email": "bad", "age": 15})
except* ValueError as eg:         # handles all ValueErrors in group
    for e in eg.exceptions:
        print(f"Value error: {e}")
except* TypeError as eg:           # handles all TypeErrors in group
    for e in eg.exceptions:
        print(f"Type error: {e}")

# ── Pre-3.11 alternative: collect and raise once ──────
class MultiError(Exception):
    def __init__(self, errors):
        self.errors = errors
        msgs = "; ".join(str(e) for e in errors)
        super().__init__(f"{len(errors)} errors: {msgs}")

def validate_all(data):
    errors = []
    for key, val in data.items():
        try:
            validate_field(key, val)
        except ValueError as e:
            errors.append(e)
    if errors:
        raise MultiError(errors)

Custom Exception Best Practices

Following these conventions makes your exceptions predictable, maintainable, and professional:

Python — best_practices.py
# ✅ DO: Name ends with Error (convention)
class PaymentError(Exception): pass
# ❌ DON'T: PaymentException, PaymentProblem, BadPayment

# ✅ DO: Always call super().__init__(message)
class GoodError(Exception):
    def __init__(self, thing):
        super().__init__(f"{thing} failed")  # ← always!
# ❌ DON'T skip super().__init__() — args will be empty!

# ✅ DO: Keep exceptions light — no business logic
class InsufficientFundsError(Exception):
    def __init__(self, balance, required):
        self.balance  = balance
        self.required = required
        super().__init__(f"Need ₹{required-balance:.2f} more")
# ❌ DON'T send emails or retry from inside __init__!

# ✅ DO: Use a docstring
class RateLimitError(Exception):
    """Raised when the API rate limit is exceeded."""
    def __init__(self, limit, reset_at):
        self.limit    = limit
        self.reset_at = reset_at
        super().__init__(f"Rate limit {limit} exceeded. Resets at {reset_at}")

# ✅ DO: Put exceptions in their own module
# mypackage/
# ├── __init__.py
# ├── exceptions.py   ← all custom exceptions here
# ├── services.py     ← imports and raises from exceptions.py
# └── api.py          ← catches from exceptions.py

# ✅ DO: Document which exceptions a function can raise
def create_order(user_id: int, items: list) -> int:
    """
    Create a new order.
    
    Raises:
        UserNotFoundError: if user_id doesn't exist
        InsufficientFundsError: if balance is too low
        InvalidItemError: if any item is unavailable
    """
    ...
Exception design checklist Name ends with Error ✓  |  Inherits from Exception ✓  |  Has a docstring ✓  |  Calls super().__init__(msg) ✓  |  Extra attributes are meaningful ✓  |  Has a clear, actionable message ✓  |  Lives in exceptions.py ✓

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all custom exception examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every custom exception example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Custom exceptions are just classes that inherit from Exception (or a specific subclass). Even a bare class MyError(Exception): pass is a valid, catchable exception.
  • Add domain context via extra attributes in __init__ — always call super().__init__(formatted_message) to set the string representation.
  • Override __str__ for human-readable messages and __repr__ for developer debug output. Good messages include the bad value and what was expected.
  • Build exception hierarchies with a module-level base class. Callers catch at the level of specificity they need — from very specific to all-module errors.
  • Name exceptions with an Error suffix (convention). Inherit from a specific built-in when appropriate — ValueError, LookupError, IOError.
  • Add a docstring. Keep exceptions simple — no business logic in __init__. Put all exceptions in a dedicated exceptions.py module.
  • Document raised exceptions in docstrings with the Raises: section.
  • Python 3.11+ ExceptionGroup and except* handle multiple simultaneous exceptions — particularly useful in async code and form validation.
⚡
Free Resource
Download our Python Custom Exceptions Cheat Sheet
Minimal to full anatomy, hierarchies, best practices, ExceptionGroup & domain patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

Calling super().__init__(message) passes the message to Exception.__init__, which stores it in self.args. Without this call:

  • str(e) and print(e) will produce an empty string
  • e.args will be an empty tuple
  • The traceback won't show your message
  • Logging and debugging become much harder

Always: super().__init__(f"Descriptive message here")

✓ Answer

A module-level base exception (e.g. AppError) lets callers choose the level of specificity when catching:

except UserNotFoundError:  # very specific
except UserError:          # all user errors
except AppError:           # any app error

It also makes your module's error contract clear — callers know they can catch AppError to handle all errors from your library safely.

✓ Answer

Exception class names should end with Error (PEP 8 convention). Use CamelCase for the class name:

  • ✅ ValidationError, NotFoundError, InsufficientFundsError
  • ❌ ValidationException, BadInput, payment_problem

The only exceptions to the "Error" suffix convention are Warning (and its subclasses) and truly exceptional base classes — but even then, most production code sticks with Error.

✓ Answer

ExceptionGroup (Python 3.11+) wraps multiple exceptions so they can be raised simultaneously. Used with except* for handling individual types from the group.

Best use cases: form validation (report all field errors at once), concurrent/async code where multiple tasks fail simultaneously, batch processing where several items fail.

Pre-3.11 equivalent: collect errors in a list and raise a custom MultiError that stores them as self.errors.

✓ Answer

Inheriting from Exception directly creates an independent exception only catchable by its name or Exception.

Inheriting from a specific built-in like ValueError means your exception is also catchable as that built-in type — useful for compatibility:

class InvalidAgeError(ValueError): pass

# Catchable as both:
except InvalidAgeError: ...  # specific
except ValueError: ...       # also catches this!

Use this when your exception semantically IS a kind of built-in error (a validation exception IS a ValueError). Use Exception directly for errors that don't fit any built-in category.

MCQ 1 of 3
What is the correct way to define a minimal custom exception named PaymentError?
MCQ 2 of 3
Which method should you override to control what print(e) displays for a custom exception?
MCQ 3 of 3
If UserNotFoundError inherits from UserError which inherits from AppError, which except clause will catch a UserNotFoundError?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel