Custom Exceptions and Raising Errors
Define custom application exceptions by subclassing Exception, trigger domain-specific errors with raise, and preserve root causes with exception chaining.
While Python ships with dozens of built-in exceptions like ValueError, KeyError, and TypeError, these errors describe low-level programming problems—not the specific business logic of your application.
Imagine building an online banking application:
- A user attempts to transfer $500, but only has $120 in their account.
- You could raise a built-in
ValueError("Not enough money").
However, using a generic ValueError causes serious problems:
- What if a different part of the transfer function raises a
ValueErrorbecause someone typed an invalid character into a postal code field? - A caller catching
except ValueError:cannot distinguish between bad user input syntax and an insufficient bank balance!
To build robust, production-grade software, you should define Custom Domain Exceptions that cleanly express the exact problem that occurred.
1. The raise Keyword: Triggering Errors Intentionally
Before defining custom errors, let’s look at how to trigger an exception intentionally using the raise statement:
def set_volume(level):
if not (0 <= level <= 100):
# Trigger an error and stop execution immediately
raise ValueError(f"Volume must be between 0 and 100. Received: {level}")
print(f"Volume adjusted to {level}%.")
set_volume(75)
# Triggering an intentional error:
# set_volume(150) # ValueError: Volume must be between 0 and 100. Received: 150
When Python hits a raise statement, normal linear execution stops immediately. Python packs the exception into memory and begins traveling up the call stack until it finds an except handler equipped to deal with it.
2. Creating a Custom Exception
In Python, creating a custom exception is remarkably simple: define a new class that inherits from Python’s built-in Exception class (learned in classes):
class InsufficientFundsError(Exception):
"""Raised when an account withdrawal exceeds available balance."""
pass
That’s it! Even with an empty body (pass), you now have a first-class, named exception:
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError(
f"Cannot withdraw ${amount:.2f}. Available balance: ${balance:.2f}"
)
return balance - amount
try:
current_balance = 100.0
withdraw(current_balance, 250.0)
except InsufficientFundsError as err:
print(f"Transaction Declined: {err}")
Output:
Transaction Declined: Cannot withdraw $250.00. Available balance: $100.00
3. Why Always Inherit from Exception (NOT BaseException)
Python organizes all its errors into an inheritance hierarchy:
BaseException
├── SystemExit (sys.exit)
├── KeyboardInterrupt (Ctrl+C in terminal)
└── Exception (All application & standard errors)
├── StandardError (ValueError, TypeError, KeyError...)
└── YourCustomError (Inherit from here!)
[!CRITICAL] Always inherit from
Exception, neverBaseException.If you subclass
BaseException, standard application exception handlers likeexcept Exception:will be unable to catch your error! Only critical system events (likeKeyboardInterruptandSystemExit) should inherit directly fromBaseException.
4. Adding Rich Data Attributes to Exceptions
Because custom exceptions are standard Python classes, you can attach custom attributes to give callers structured data about the failure:
class OrderValidationError(Exception):
def __init__(self, item_id, requested_qty, available_qty):
message = (
f"Item #{item_id}: Requested {requested_qty} units, "
f"but only {available_qty} are currently in stock."
)
super().__init__(message)
# Store structured data attributes on the exception object
self.item_id = item_id
self.requested_qty = requested_qty
self.available_qty = available_qty
def process_order(item_id, qty):
in_stock = 3
if qty > in_stock:
raise OrderValidationError(item_id, qty, in_stock)
try:
process_order(849, 10)
except OrderValidationError as err:
print(f"Log: {err}")
print(f"Restock notification triggered for Item ID: {err.item_id}")
print(f"Deficit amount: {err.requested_qty - err.available_qty} units")
Output:
Log: Item #849: Requested 10 units, but only 3 are currently in stock.
Restock notification triggered for Item ID: 849
Deficit amount: 7 units
5. Architectural Pattern: The Application Exception Hierarchy
In professional libraries and web frameworks (like Django or FastAPI), engineers never create disconnected, isolated exceptions. They create an exception tree with a single base exception for the whole module:
# 1. Base error for the entire payment module
class PaymentGatewayError(Exception):
"""Base exception for all payment gateway failures."""
pass
# 2. Specific domain sub-errors
class CardExpiredError(PaymentGatewayError):
pass
class FraudDetectedError(PaymentGatewayError):
pass
class GatewayTimeoutError(PaymentGatewayError):
pass
The Caller Advantage
Now, callers have the ultimate flexibility:
try:
process_payment(card_info)
except CardExpiredError:
# Handle specific user-correctable error
prompt_user_for_new_card()
except PaymentGatewayError as err:
# Catch ALL other payment failures in one unified handler!
log_internal_payment_failure(err)
6. Exception Chaining with raise ... from
When writing backend systems, you often catch a low-level error (like an HTTP connection failure) and want to re-raise a high-level application error, without losing the original root cause.
Use the from keyword to chain exceptions:
def fetch_cloud_config():
try:
# Simulate network failure
import urllib.request
urllib.request.urlopen("https://invalid-non-existent-domain.internal")
except Exception as original_err:
# Re-raise as custom domain error while preserving root cause
raise PaymentGatewayError("Failed to synchronize payment configuration") from original_err
When Python prints the traceback, it will explicitly state:
The above exception was the direct cause of the following exception:
This gives developers the best of both worlds: clean domain architecture for users, and the full root-cause traceback for debugging engineers!
Summary & What’s Next
- Use
raiseto intentionally emit an error when conditions are invalid. - Custom exceptions should always inherit from
Exception. - Store structured metadata on custom exceptions using
__init__. - Build application-level exception hierarchies so callers can catch all module errors with a single base class.
- Use
raise CustomError from original_errto preserve root causes.
Now that you know how to build and raise errors, learn how to diagnose, trace, and inspect bugs using interactive tools in debugging.