Fundamentals 6 min read

Creating and Using Custom Exceptions in Python

This article explains why custom exceptions are needed in Python, shows how to define them—including simple, information‑rich, and subclassed variants—provides practical code examples such as inventory‑shortage and API‑request errors, and outlines best practices for naming, documentation, and inheritance.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Creating and Using Custom Exceptions in Python

In Python, exception handling is essential for robust programs. Besides built‑in exceptions such as ValueError , TypeError , and IndexError , developers can create custom exceptions to capture specific business‑logic errors more precisely.

1. Why custom exceptions?

Built‑in exceptions cover many common errors, but custom ones provide:

Clearer error classification, e.g., InsufficientStockError conveys the problem better than a generic ValueError .

Business‑logic‑specific errors, such as InvalidTransactionError in a banking system.

Improved code readability and maintainability.

2. How to define custom exceptions?

All Python exceptions must inherit from BaseException , though inheriting from Exception or its subclasses is recommended. Common implementations include:

(1) Simplest custom exception

class MyCustomError(Exception):
    """Custom exception example"""
    pass

Raise it directly:

raise MyCustomError("A custom error occurred!")

(2) Custom exception with extra information

Override __init__ to store additional context:

class ValidationError(Exception):
    """Raised when data validation fails"""
    def __init__(self, message, field):
        super().__init__(message)  # call parent initializer
        self.field = field          # store field name

Usage example:

try:
    raise ValidationError("Invalid username", field="username")
except ValidationError as e:
    print(f"Error in field {e.field}: {e}")

(3) Inheriting from an existing exception

If a built‑in exception is close to your needs, subclass it:

class PositiveNumberError(ValueError):
    """Number must be positive"""
    pass

Usage example:

def check_positive(num):
    if num <= 0:
        raise PositiveNumberError(f"Number {num} must be positive!")
check_positive(-5)  # triggers PositiveNumberError

3. Real‑world scenarios

Scenario 1: E‑commerce insufficient stock

class InsufficientStockError(Exception):
    def __init__(self, item_name, available, requested):
        self.item_name = item_name
        self.available = available
        self.requested = requested
        super().__init__(f"Item {item_name} out of stock! Available {available}, requested {requested}")

def purchase_item(item_name, stock, quantity):
    if quantity > stock:
        raise InsufficientStockError(item_name, stock, quantity)
    print(f"Successfully purchased {quantity} of {item_name}")

Test code:

try:
    purchase_item("Python Book", stock=5, quantity=10)
except InsufficientStockError as e:
    print(e)  # Output: Item Python Book out of stock! Available 5, requested 10

Scenario 2: API request failure

class APIRequestError(Exception):
    """API request failed"""
    def __init__(self, url, status_code, response=None):
        self.url = url
        self.status_code = status_code
        self.response = response
        super().__init__(f"Request {url} failed, status code: {status_code}")

Simulated API call:

try:
    raise APIRequestError("https://api.example.com/data", 404)
except APIRequestError as e:
    print(f"API error: {e}, response: {e.response}")

4. Best practices

Name exception classes with an Error suffix, e.g., InvalidInputError .

Include rich information (error field, status code, etc.) to aid debugging.

Prefer inheriting from Exception or a more specific built‑in exception.

Document each custom exception with a docstring describing its purpose and trigger conditions.

5. Summary

Custom exceptions are an advanced Python technique that enables more precise error typing, richer error information, and better code readability and maintainability. By inheriting from Exception and adding tailored logic, developers can create exception types suited to diverse business scenarios, leading to more elegant and professional error handling.

PythonException HandlingBest PracticesCustom ExceptionsError Design
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.