IC Improve Code Recipes

Recipe 5.3 · Python

Custom Exceptions Worth Having

The Python listings are conversions of the book's C# code to Python 3.12. Each file's header says what it needs to run. The explanations were written for the C# version, so some names in the text refer to .NET.

Problem

Some code bases have no custom exceptions, so everything is Exception("Customer not found") and callers parse messages to decide what to do. Others have one exception class per method, sixty of them, none of which any caller catches. Neither helps.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Throwing generic exceptions and matching on message text (p105_r5_3_generic_exception_message_matching_before.py)
"""Throwing generic exceptions and matching on message text

Source: ImproveCode, Chapter 5, Recipe 5.3 "Custom Exceptions Worth Having"
Section: The way it's often written
Book page: 105  -- original C# listing
Converted from C# to Python.
ANTI-PATTERN: kept deliberately faithful to the C# 'not to copy' example; do not use.
Both halves of the C# fragment are wrapped in functions; `response` stands in for
the ASP.NET Response object.
"""

from __future__ import annotations

from typing import Any, Callable


def load(customer: Any) -> Any:
    # Not this: callers have to compare strings.
    if customer is None:
        raise Exception("Customer not found")
    return customer


def handle(action: Callable[[], Any], response: Any) -> None:
    # ...and somewhere up the stack:
    try:
        action()
    except Exception as ex:
        if "not found" in str(ex):
            response.status_code = 404

The improved recipe

Write a small set of exceptions that map to decisions a caller actually makes: not found, conflict, business rule violated. Give them a stable error code and the data a handler needs.

Usage:

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Application exception hierarchy with stable error codes (p106_r5_3_app_exception_hierarchy.py)
"""Application exception hierarchy with stable error codes

Source: ImproveCode, Chapter 5, Recipe 5.3 "Custom Exceptions Worth Having"
Section: The improved recipe
Book page: 106  -- original C# listing
Converted from C# to Python.
The inner exception is stored as __cause__ (what `raise X from inner` does);
the abstract base uses ABC so it cannot be raised directly.
"""

from __future__ import annotations

from abc import ABC
from typing import Any


class AppException(Exception, ABC):
    """Base type for failures the application expects
    and knows how to report."""

    def __init__(self, error_code: str, message: str,
                 inner: BaseException | None = None) -> None:
        if type(self) is AppException:
            raise TypeError("AppException is abstract")
        super().__init__(message)
        self.__cause__ = inner
        # Stable, machine-readable code, e.g. "not_found".
        self.error_code = error_code

    @property
    def message(self) -> str:
        return str(self)


class NotFoundException(AppException):
    def __init__(self, entity: str, key: Any) -> None:
        super().__init__("not_found", f"{entity} '{key}' was not found.")
        self.entity = entity
        self.key = key


class ConflictException(AppException):
    def __init__(self, message: str, inner: BaseException | None = None) -> None:
        super().__init__("conflict", message, inner)


class BusinessRuleException(AppException):
    def __init__(self, rule: str, message: str) -> None:
        super().__init__(rule, message)

Requirements: Python 3.12+. Standard library only, nothing to install.

Python Raising NotFound and business-rule exceptions from a service method (p107_r5_3_raise_not_found_and_rule_errors.py)
"""Raising NotFound and business-rule exceptions from a service method

Source: ImproveCode, Chapter 5, Recipe 5.3 "Custom Exceptions Worth Having"
Section: The improved recipe
Book page: 107  -- original C# listing
Converted from C# to Python.
The `?? throw` expression becomes an explicit None check; the exception classes
come from p106_r5_3_app_exception_hierarchy.py (minimal copies here for a self-contained file).
"""

from __future__ import annotations

from typing import Any


class NotFoundException(Exception):
    def __init__(self, entity: str, key: Any) -> None:
        super().__init__(f"{entity} '{key}' was not found.")


class BusinessRuleException(Exception):
    def __init__(self, rule: str, message: str) -> None:
        super().__init__(message)
        self.error_code = rule


async def check_order(repository: Any, id: int, order: Any) -> Any:
    customer = await repository.find(id)
    if customer is None:
        raise NotFoundException("Customer", id)

    if order.total > customer.credit_limit:
        raise BusinessRuleException(
            "credit_limit_exceeded",
            f"Order total ${order.total:,.2f} exceeds the credit limit.")

    return customer

How it works

The test for whether an exception class is worth having is simple: does some caller catch it, or does the global handler treat it differently? NotFoundException becomes HTTP 404, ConflictException becomes 409 (a concurrent update, a duplicate key), BusinessRuleException becomes 422. Everything else is a 500. Three classes cover most of what a line-of-business app needs.

The common base class lets the global handler (Recipe 5.4) recognize every expected failure with one type check, and ErrorCode gives API clients something stable to switch on. Messages get reworded; codes shouldn't.

The messages are safe to show to the user because the code that throws them writes them for that purpose. That is the real distinction: an AppException message is part of your product, while a SqlException message is an internal detail that must never reach the browser.

Wrapping a database exception into ConflictException (for example, catching a unique-key violation, SQL Server error 2627 or 2601, and rethrowing) keeps the inner exception for the log and gives the caller a meaningful type.

Variations and pitfalls

  • Use the built-in types when they fit: ArgumentException and ArgumentNullException for bad arguments, InvalidOperationException for calls made in the wrong state, NotSupportedException, TimeoutException. Don't write InvalidCustomerIdException.
  • Don't throw AppException subclasses for programming errors. A null that should never be null is a bug, and it should surface as a 500 with a stack trace.
  • Validation failures with several field errors are better modeled as a validation result than as an exception. Chapter 8 covers that.
  • The old pattern of adding a serialization constructor and [Serializable] is obsolete in .NET 8 (warning SYSLIB0051). Binary serialization of exceptions is no longer a goal, so leave them out in new code.

On .NET Framework

On .NET Framework, exceptions that cross AppDomain or remoting boundaries still need [Serializable] and the (SerializationInfo, StreamingContext) constructor. If you share these classes between a 4.8 service and a modern app through a .NET Standard library, add them behind #if NETFRAMEWORK.