Custom Exceptions & Exception Chaining
Published by Brayan K
A custom exception is your own class that subclasses Exception, giving a failure a meaningful name callers can catch precisely — and exception chaining (raise ... from ...) links a high-level error to the lower-level cause that triggered it.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Make the failure part of the function’s public contract
A caller should not have to inspect the words in an error message to decide what happened. Give a domain failure a type, then let the caller handle that type. Derive ordinary application errors from Exception or a suitable subclass. BaseException also includes termination signals such as KeyboardInterrupt and SystemExit, which ordinary application handlers should usually let through.
class ReservationError(Exception):
pass
class CapacityError(ReservationError):
pass
def reserve(requested, available):
if requested > available:
raise CapacityError("not enough seats")
return available - requested
for requested in [2, 5]:
try:
print("Remaining:", reserve(requested, 3))
except CapacityError as error:
print("Rejected:", error)
# ✅ Expected output:
# Remaining: 1
# Rejected: not enough seatsThe success result is a remaining seat count; failure is a separate control-flow path. A sentinel such as -1 would require every caller to remember an unrelated convention. Basic try/except flow, else and finally are owned by Exception Handling. Here the design question is which failure types the caller can reliably distinguish.
class CapacityError(Exception):
pass
raise CapacityError("not enough seats")
# ✅ Expected error:
# CapacityError: not enough seatsStore structured context without making callers parse the message
class CapacityError(Exception):
def __init__(self, requested, available):
self.requested = requested
self.available = available
super().__init__(f"requested {requested}; available {available}")
try:
raise CapacityError(5, 3)
except CapacityError as error:
print(error.requested - error.available)
print(str(error))
print(error.args)
# ✅ Expected output:
# 2
# requested 5; available 3
# ('requested 5; available 3',)The fields give the handler a stable interface. Calling the base initializer supplies the message used by str(error) and keeps args coherent. Treat the message as human-readable text rather than an API to split with string operations. Avoid putting passwords or other sensitive input into exception messages that may later be logged.
A hierarchy is useful when some callers need a broad category and others need a specific refusal. Catch the narrow case first when handlers overlap; matching is based on inheritance, not on class names that merely look related.
class BookingError(Exception):
pass
class CapacityError(BookingError):
pass
class ClosedError(BookingError):
pass
for error in [CapacityError("full"), ClosedError("closed")]:
try:
raise error
except CapacityError:
print("offer another time")
except BookingError:
print("show booking refusal")
# ✅ Expected output:
# offer another time
# show booking refusalTranslate an implementation error and keep its cause
A parser may fail with ValueError, while its caller deals in configuration or reservation errors. At that boundary, raise a domain error from the lower-level exception. The caller sees the domain contract and the traceback still records the cause. Keep the try block small so unrelated bugs are not mislabeled as invalid input.
class SettingError(Exception):
pass
def read_limit(text):
try:
value = int(text)
except ValueError as error:
raise SettingError("limit must be a whole number") from error
if value < 1:
raise SettingError("limit must be positive")
return value
try:
read_limit("many")
except SettingError as error:
print(str(error))
print(type(error.__cause__).__name__)
print(error.__cause__ is error.__context__)
print(error.__suppress_context__)
# ✅ Expected output:
# limit must be a whole number
# ValueError
# True
# TrueThe explicit cause is available through __cause__. __context__ also records an exception active when the new one was raised. The suppress-context flag controls which chain is displayed; it does not mean the underlying failure vanished. A positive-range refusal is a separate validation decision after parsing succeeds.
try:
try:
int("many")
except ValueError:
raise RuntimeError("conversion failed")
except RuntimeError as error:
print(type(error.__context__).__name__)
print(error.__cause__ is None)
print(error.__suppress_context__)
# ✅ Expected output:
# ValueError
# True
# FalseHiding a displayed chain does not erase its history
try:
try:
{}["limit"]
except KeyError:
raise ValueError("limit is required") from None
except ValueError as error:
print(str(error))
print(error.__cause__ is None)
print(type(error.__context__).__name__)
print(error.__suppress_context__)
# ✅ Expected output:
# limit is required
# True
# KeyError
# TrueUse from None only when suppressing implementation detail is a deliberate interface choice. The original exception remains inspectable as context, so this is not a way to scrub secrets. If a caller needs diagnostic history, explicit chaining is normally clearer than discarding the visible chain.
When an intermediate layer has no new failure to report, a bare raise rethrows the active exception. It preserves the failure identity instead of wrapping every layer in a new type.
original = ValueError("invalid row")
try:
try:
raise original
except ValueError as error:
error.add_note("while importing the sample table")
raise
except ValueError as error:
print(error is original)
print(str(error))
print(error.__notes__)
# ✅ Expected output:
# True
# invalid row
# ['while importing the sample table']add_note is available in Python 3.11 and later. Notes supplement the message without changing args or the error type. Their display in a traceback is useful for context, but the code above prints the note list directly to keep the result independent of traceback formatting.
raise
# ✅ Expected error:
# RuntimeError: No active exception to reraiseAttach the original conversion error to a setting failure
Complete the base class, the caught conversion type and the explicit cause. The caller must receive SettingError while retaining the ValueError for diagnostics.
class SettingError(___):
pass
def parse_count(text):
try:
return int(text)
except ___ as error:
raise SettingError("count is invalid") from ___
try:
parse_count("several")
except SettingError as error:
print(type(error).__name__)
print(type(error.__cause__).__name__)
# 👉 replace ___ with Exception
# 👉 replace ___ with ValueError
# 👉 replace ___ with error
# ✅ Expected output:
# SettingError
# ValueErrorSeparate a malformed quantity from a rejected quantity
Write OrderError as a base for QuantityFormatError and QuantityRangeError. parse_quantity should convert text to int, chain conversion failures as QuantityFormatError, and reject values below one with QuantityRangeError after conversion. The range error should store the rejected value in a value attribute. Process "3", "many" and "0" in order. Print accepted values, print the format-error cause type, and print the rejected numeric value. Catch only the domain errors you expect.
class OrderError(Exception):
pass
class QuantityFormatError(OrderError):
pass
class QuantityRangeError(OrderError):
def __init__(self, value):
self.value = value
super().__init__("quantity must be positive")
def parse_quantity(text):
try:
value = int(text)
except ValueError as error:
raise QuantityFormatError("quantity must be a whole number") from error
if value < 1:
raise QuantityRangeError(value)
return value
for text in ["3", "many", "0"]:
try:
print("Accepted:", parse_quantity(text))
except QuantityFormatError as error:
print("Format cause:", type(error.__cause__).__name__)
except QuantityRangeError as error:
print("Rejected value:", error.value)
# ✅ Expected output:
# Accepted: 3
# Format cause: ValueError
# Rejected value: 0The distinction lets the caller choose a useful response without parsing messages. Neither handler catches unexpected programming failures, and the range check cannot accidentally relabel its own exception as a conversion failure.
Practice quiz
Which base should ordinary application-defined failures usually extend?
- Exception
- BaseException directly
- SystemExit
- object
Answer: Exception. Exception keeps ordinary errors separate from termination signals.
What does this program print? class Failure(Exception): pass error = Failure("bad input") print(str(error)) print(error.args)
- ('bad input',) bad input
- Failure []
- bad input ('bad input',)
- bad input []
Answer: bad input ('bad input',). The base initializer stores positional arguments and formats the single message.
What does raise SettingError("bad") from error preserve explicitly?
- The caller’s local variables
- A successful return value
- Only the message text
- The original exception in __cause__
Answer: The original exception in __cause__. The cause is an exception object, not a copied message.
What does this program print? try: try: int("x") except ValueError: raise RuntimeError("bad") from None except RuntimeError as error: print(type(error.__context__).__name__) print(error.__suppress_context__)
- NoneType True
- ValueError True
- ValueError False
- NoneType False
Answer: ValueError True. Suppressing display leaves implicit context available.
What does this program print? class BaseError(Exception): pass class ChildError(BaseError): pass try: raise ChildError("x") except BaseError: print("base") except ChildError: print("child")
- child
- base child
- base
- uncaught
Answer: base. The first matching handler wins, including a superclass match.
Why put the range validation after the narrow conversion try block?
- To make int accept negative text
- To avoid mislabeling a domain validation failure as a conversion failure
- To stop exceptions propagating
- To remove the need for a custom type
Answer: To avoid mislabeling a domain validation failure as a conversion failure. A small boundary handles only the operation whose failure it translates.
What does this program print? error = ValueError("bad") error.add_note("row 2") print(str(error)) print(error.__notes__)
- bad ['row 2']
- bad row 2
- bad row 2 []
- ValueError ['row 2']
Answer: bad ['row 2']. Notes supplement the exception without replacing its message.
Which error ends this program? raise
- None
- ValueError: no exception
- TypeError: exceptions must derive from BaseException
- RuntimeError: No active exception to reraise
Answer: RuntimeError: No active exception to reraise. Bare raise requires an active handled exception.
Continue this course
- Previous: Scope: global, nonlocal & LEGB
- Next: Time Zones with zoneinfo — Aware datetimes, converting between zones, and storing UTC correctly
- Quick reference: Python cheat sheet › Exceptions
- From the blog: Error Handling Best Practices in Python