Python Custom Exceptions

Learn Python Custom Exceptions with practical examples, explanations, best practices, and real-world coding techniques.

Python custom exceptions allow you to define application-specific error types that communicate exactly what went wrong. Python already provides many built-in exceptions such as ValueError, TypeError, and FileNotFoundError. These are useful for general programming failures, but real applications often contain domain rules that deserve more meaningful exception names.

For example, an e-commerce application might need to distinguish between insufficient stock, an expired coupon, and an invalid order state. An authentication system may need separate errors for an expired session or an account that is locked. Custom exceptions make those situations explicit and allow callers to handle them independently.

Why Use Custom Exceptions?

A custom exception gives a failure a meaningful identity. Instead of making a caller inspect error-message text, the caller can catch a specific exception class.

  • Make domain-specific failures easy to recognize.
  • Allow different errors to have different handling behavior.
  • Keep business rules separate from presentation logic.
  • Make application code easier to test.
  • Provide a stable contract between different layers of an application.

Creating a Basic Custom Exception

A custom exception is usually created by defining a class that inherits from Exception or one of its more appropriate subclasses.

class InsufficientStockError(Exception):
    pass

The pass statement is enough when the exception only needs a distinct type. It can then be raised like any other exception.

class InsufficientStockError(Exception):
    pass


def reserve_product(stock: int, quantity: int) -> None:
    if quantity > stock:
        raise InsufficientStockError("Not enough stock available")


try:
    reserve_product(5, 8)
except InsufficientStockError as error:
    print(error)

The important part is not the number of lines in the exception class. The important part is that the exception now has its own type and can be identified independently from unrelated errors.

Inherit from an Appropriate Built-in Exception

Custom exceptions do not always need to inherit directly from Exception. Choosing an appropriate built-in base class can make the exception more descriptive.

class InvalidQuantityError(ValueError):
    pass

This tells readers that the problem is related to an invalid value. The custom exception can still be caught specifically, while code that handles ValueError more generally can also recognize it.

Base Exception Useful For
Exception General application-specific errors.
ValueError Invalid or unacceptable values.
TypeError Invalid type-related operations.
LookupError Lookup-related failures such as missing keys or indexes.
OSError Application-specific filesystem or operating-system failures.

Custom Exception Naming

Python exception class names normally use PascalCase and end with Error, although the exact name should communicate the failure clearly.

class InvalidOrderError(ValueError):
    pass


class PaymentRequiredError(Exception):
    pass


class ExpiredSessionError(Exception):
    pass

A name such as SomethingWentWrongError is technically possible but does not communicate enough information. Prefer names that describe a meaningful category of failure.

Adding a Useful Error Message

The simplest custom exception can rely on the message supplied when the exception is raised.

class InvalidAgeError(ValueError):
    pass


def register_user(age: int) -> None:
    if age < 18:
        raise InvalidAgeError("User must be at least 18 years old")


try:
    register_user(16)
except InvalidAgeError as error:
    print(error)

This pattern is often enough. The exception type communicates the category of failure, while the message provides details about the individual occurrence.

Custom Exception Attributes

Sometimes a message alone is not enough. You may need structured information such as an order ID, requested quantity, available quantity, or an error code. Custom exception classes can store additional attributes.

class InsufficientStockError(Exception):
    def __init__(self, product_id: int, requested: int, available: int):
        self.product_id = product_id
        self.requested = requested
        self.available = available

        super().__init__(
            f"Product {product_id} has only "
            f"{available} items available, but {requested} were requested."
        )


try:
    raise InsufficientStockError(
        product_id=101,
        requested=8,
        available=5
    )
except InsufficientStockError as error:
    print(error)
    print(f"Product: {error.product_id}")
    print(f"Requested: {error.requested}")
    print(f"Available: {error.available}")

Structured attributes are particularly useful when an upper layer needs to make a decision based on the failure rather than parsing the exception message.

Creating an Exception Hierarchy

Larger applications can define a family of related exceptions under a shared base class. This allows callers to catch either a particular error or an entire category of related errors.

class OrderError(Exception):
    pass


class InvalidOrderError(OrderError):
    pass


class OrderNotFoundError(OrderError):
    pass


class OrderAlreadyCancelledError(OrderError):
    pass

A caller can now handle one specific error:

try:
    process_order()
except OrderNotFoundError:
    print("Order was not found.")

Or it can handle all order-related failures together:

try:
    process_order()
except OrderError as error:
    print(f"Order processing failed: {error}")

This hierarchy can become a useful contract between services, business logic, and API layers.

Custom Exceptions in Business Logic

One of the strongest use cases for custom exceptions is representing business rules. Consider a banking operation where an account cannot withdraw more money than its available balance.

class InsufficientFundsError(ValueError):
    pass


class BankAccount:
    def __init__(self, balance: float):
        self.balance = balance

    def withdraw(self, amount: float) -> None:
        if amount <= 0:
            raise ValueError("Amount must be positive")

        if amount > self.balance:
            raise InsufficientFundsError(
                "Insufficient funds for this withdrawal"
            )

        self.balance -= amount


account = BankAccount(500)

try:
    account.withdraw(700)
except InsufficientFundsError as error:
    print(error)

The business logic does not need to know whether the failure will eventually become a command-line message, an API response, a log entry, or a user-interface notification. It simply communicates the domain failure through a meaningful exception.

Custom Exceptions at an API Boundary

In a web application, an exception can travel upward through the application until an appropriate boundary handles it. For example, a service might raise OrderNotFoundError, while an API layer translates that domain error into an appropriate HTTP response.

class OrderError(Exception):
    pass


class OrderNotFoundError(OrderError):
    pass


def get_order(order_id: int):
    order = None

    if order is None:
        raise OrderNotFoundError(
            f"Order {order_id} was not found"
        )

    return order


try:
    order = get_order(42)
except OrderNotFoundError:
    print("Return a not-found response")

The exact HTTP framework response is a separate concern. Keeping the domain exception independent from the web framework makes the business code easier to reuse and test.

Exception Chaining with Custom Exceptions

Sometimes the original exception comes from a lower-level library or operating-system operation, while your application needs to expose a more meaningful domain error. Python supports exception chaining with from.

class UserDataError(Exception):
    pass


def load_user_data():
    try:
        with open("users.json", "r", encoding="utf-8") as file:
            return file.read()
    except OSError as error:
        raise UserDataError(
            "Unable to load user data"
        ) from error


try:
    load_user_data()
except UserDataError as error:
    print(error)

The custom exception gives the caller a meaningful application-level error, while the original exception remains available as the underlying cause for diagnostics.

When Not to Create a Custom Exception

Custom exceptions are useful, but creating a new exception class for every small problem can make an application unnecessarily complex.

Use a built-in exception when it already describes the problem accurately. For example, a function receiving a negative quantity may reasonably raise ValueError if there is no need for callers to distinguish that condition from other invalid values.

Create a custom exception when the failure has domain meaning, requires different handling, belongs to a recognizable category, or forms part of an application-level contract.

Custom Exception vs Built-in Exception

Situation Recommended Choice
Invalid numeric or textual value ValueError
Wrong Python object type TypeError
Application-specific domain failure Custom exception
Several related domain failures Custom exception hierarchy

Testing Custom Exceptions

Custom exceptions are easy to test because the exception type itself provides a precise assertion target. A test should verify that invalid operations raise the expected exception rather than depending only on an error message.

import pytest


class InvalidQuantityError(ValueError):
    pass


def reserve(quantity: int) -> None:
    if quantity < 1:
        raise InvalidQuantityError(
            "Quantity must be positive"
        )


def test_invalid_quantity():
    with pytest.raises(InvalidQuantityError):
        reserve(0)

Testing the exception type keeps the test aligned with the behavior that matters. Message assertions can still be useful when the exact message is part of the application's expected behavior.

Common Mistakes

Creating Too Many Exception Types

Do not create a separate class for every minor variation unless callers need to handle those failures differently.

Using Generic Names

Names such as MyError or GeneralError provide little information about the failure.

Parsing Error Messages

Callers should generally react to exception types or structured attributes instead of searching strings inside messages.

Catching Everything

A custom exception does not justify broad except Exception handlers everywhere. Catch failures where they can actually be handled.

Best Practices for Python Custom Exceptions

  • Inherit from Exception or a more appropriate built-in exception.
  • Use clear names that describe the domain failure.
  • End exception class names with Error when appropriate.
  • Keep simple exceptions simple; add custom attributes only when they provide useful structured information.
  • Create a shared base exception when several related failures belong to the same domain.
  • Raise exceptions close to the point where the invalid state is detected.
  • Catch exceptions at a layer that knows how to respond to them.
  • Use exception chaining when translating low-level failures into higher-level application errors.
  • Test the exception type and important structured data rather than relying only on formatted messages.

A Practical Application Example

The following example combines a custom hierarchy, structured data, validation, and handling into a small order-processing workflow.

class OrderError(Exception):
    pass


class InvalidOrderError(OrderError):
    pass


class InsufficientStockError(OrderError):
    def __init__(self, available: int, requested: int):
        self.available = available
        self.requested = requested

        super().__init__(
            f"Only {available} items are available."
        )


def place_order(stock: int, quantity: int) -> str:
    if quantity < 1:
        raise InvalidOrderError(
            "Order quantity must be positive"
        )

    if quantity > stock:
        raise InsufficientStockError(
            available=stock,
            requested=quantity
        )

    return "Order placed successfully"


try:
    result = place_order(5, 8)
    print(result)

except InsufficientStockError as error:
    print(
        f"Stock problem: requested "
        f"{error.requested}, available {error.available}"
    )

except InvalidOrderError as error:
    print(f"Invalid order: {error}")

except OrderError as error:
    print(f"Order failed: {error}")

This structure scales naturally as an application grows. New order-related exceptions can inherit from OrderError without forcing every caller to know about every individual failure type.

Summary

Python custom exceptions provide a clean way to represent failures that have meaning within a specific application or business domain. A custom exception can be as simple as an empty subclass of Exception, or it can contain structured attributes and participate in a larger exception hierarchy.

The key principle is to create custom exceptions when they make application behavior clearer. Use built-in exceptions for general problems, create domain-specific exceptions when callers need to distinguish meaningful business failures, and allow higher layers to decide how those failures should be handled.

Code Examples

Basic Custom Exception

python
class InvalidQuantityError(ValueError):
    pass


def reserve(quantity: int) -> None:
    if quantity < 1:
        raise InvalidQuantityError(
            "Quantity must be positive"
        )


try:
    reserve(0)
except InvalidQuantityError as error:
    print(error)
    

Custom Exception with Attributes

python
class InsufficientStockError(Exception):
    def __init__(self, product_id: int, requested: int, available: int):
        self.product_id = product_id
        self.requested = requested
        self.available = available

        super().__init__(
            f"Product {product_id} has only "
            f"{available} items available."
        )


try:
    raise InsufficientStockError(
        product_id=101,
        requested=8,
        available=5
    )
except InsufficientStockError as error:
    print(error)
    print(error.product_id)
    print(error.requested)
    print(error.available)
    

Custom Exception Hierarchy

python
class OrderError(Exception):
    pass


class InvalidOrderError(OrderError):
    pass


class OrderNotFoundError(OrderError):
    pass


try:
    raise OrderNotFoundError("Order does not exist.")
except OrderNotFoundError as error:
    print(f"Specific error: {error}")
except OrderError as error:
    print(f"General order error: {error}")
    

Exception Chaining

python
class ConfigurationError(Exception):
    pass


def load_config():
    try:
        with open("config.json", "r", encoding="utf-8") as file:
            return file.read()
    except OSError as error:
        raise ConfigurationError(
            "Unable to load configuration"
        ) from error


try:
    load_config()
except ConfigurationError as error:
    print(error)
    

Business Rule Exception

python
class InsufficientFundsError(ValueError):
    pass


def withdraw(balance: float, amount: float) -> float:
    if amount <= 0:
        raise ValueError("Amount must be positive")

    if amount > balance:
        raise InsufficientFundsError(
            "Insufficient funds"
        )

    return balance - amount


try:
    balance = withdraw(500, 700)
    print(balance)
except InsufficientFundsError as error:
    print(f"Withdrawal failed: {error}")
    

Pro Tip

Create a custom exception when the failure has meaningful domain semantics or needs different handling. Prefer exception types and structured attributes over making callers parse error-message strings.

More Python lessons

🎨 IgKnight Docs

Master HTML, CSS, JS, Python, .NET and more with easy-to-follow lessons and practical code examples.

© 2025 IgKnight Learning Platform. All rights reserved.