Python Custom Exceptions: Hierarchies, Messages, and Chaining
Introduction
Python custom exceptions give a business failure its own type. An order service can distinguish insufficient stock from a declined payment, while a shared parent class lets the interface handle the package’s expected failures together.
This lesson covers objective 2.2 of PCAP-31-03: extending the exception hierarchy. It completes the Exceptions section (14% of the score, 5 of 40 items) after handler selection, propagation, and cleanup. You will design a small hierarchy, attach useful data, and preserve a technical cause when translating an error.
Learning objectives
After this lesson you can:
- Define an exception class by inheriting from
Exceptionor a more specific built-in class. - Explain why custom exceptions should not inherit from
BaseExceptiondirectly. - Add attributes and a custom
__init__, and predict the effect onargsandstr(). - Build a two-level hierarchy with a common base class and catch it with one handler.
- Choose the right parent class so that existing handlers keep working.
- Combine custom exceptions with
raise ... fromand re-raising.
The smallest custom exception
An exception object is an instance of a class derived from BaseException. For ordinary application errors, define that class under Exception. Review Python exception hierarchies and handler order before choosing its parent.
class InsufficientStockError(Exception):
pass
def reserve(stock, quantity):
if quantity > stock:
raise InsufficientStockError("not enough items")
return stock - quantity
try:
reserve(3, 5)
except InsufficientStockError as err:
print("problem:", err) # problem: not enough itemsThe class body is empty, yet the exception already behaves like a built-in one. It can be raised with or without arguments, caught by name, bound with as, and inspected through args. The constructor inherited from BaseException accepts any number of positional arguments and stores them in args.
e = InsufficientStockError("a", 2)
print(e.args) # ('a', 2)
print(repr(e)) # InsufficientStockError('a', 2)
print(InsufficientStockError().args) # ()You can check the lineage with __mro__:
print([cls.__name__ for cls in InsufficientStockError.__mro__])
# ['InsufficientStockError', 'Exception', 'BaseException', 'object']Why inherit from Exception, not BaseException
BaseException is the root of the tree and also the parent of SystemExit and KeyboardInterrupt. Code that writes except Exception: deliberately lets those two pass so that a program can be stopped. If you inherited your domain error directly from BaseException, that common handler would no longer catch it, and a program could terminate unexpectedly. Rule of thumb: user-defined errors derive from Exception (or one of its subclasses), never from BaseException.
Naming and organising exceptions
Python style uses a descriptive name ending in Error for failures (InsufficientStockError) and, rarely, Warning or no suffix for other conditions. Group related exceptions under a common base class for the module or package.
class ShopError(Exception):
"""Base class for the shop package’s declared domain errors."""
class OutOfStockError(ShopError):
pass
class PaymentRefusedError(ShopError):
pass
class UnknownProductError(ShopError, KeyError):
passThis gives callers two levels of choice:
try:
checkout(cart)
except OutOfStockError:
suggest_alternatives(cart)
except ShopError as err:
log_and_notify(err)The first handler deals with one specific situation. The second catches the other declared errors derived from ShopError, while an unrelated TypeError still propagates. Because the specific class comes first, it is not hidden by its parent, exactly as in the ordering rule you learned in lesson 1.
UnknownProductError above has two parents. Python allows multiple inheritance, so an UnknownProductError is at the same time a ShopError and a KeyError (and therefore a LookupError). Existing code that already catches KeyError for missing products will still work. This example demonstrates handler matching, rather than a recommended default design. Python’s documentation recommends one exception base: multiple bases can conflict in argument handling or memory layout, and compatibility can change between versions.
Choosing the parent class
| If the failure is... | Good parent | Reason |
|---|---|---|
| A generic domain rule violation | Exception or your package base |
no built-in matches |
| A wrong value passed by the caller | ValueError |
code already catching ValueError keeps working |
| A wrong type | TypeError |
same reasoning |
| A missing item in a mapping | KeyError or LookupError |
callers can use one LookupError handler |
| An I/O problem | OSError |
file handlers apply |
| An internal inconsistency | RuntimeError |
signals a programming or state error |
Choosing a built-in parent is not required, but it can make your class fit existing handlers.
Adding data to an exception
A message is often not enough. A handler may need the product code, the missing quantity or an error code. Add attributes in __init__ and call the parent constructor so that args and str() stay meaningful.
class InsufficientStockError(ShopError):
def __init__(self, sku, requested, available):
super().__init__(f"{sku}: requested {requested}, available {available}")
self.sku = sku
self.requested = requested
self.available = available
@property
def missing(self):
return self.requested - self.available
try:
raise InsufficientStockError("A-17", 10, 4)
except InsufficientStockError as err:
print(err) # A-17: requested 10, available 4
print(err.args) # ('A-17: requested 10, available 4',)
print(err.missing) # 6Observe the effect of super().__init__(message): args contains only the message, and str(err) is that message.
What if you forget super().__init__?
In the following ordinary subclass, inherited exception construction records the positional arguments before Quiet.__init__ runs. CPython does this in BaseException.__new__. A custom allocator or explicit changes to args could alter that behavior.
class Quiet(Exception):
def __init__(self, code, text):
self.code = code # no super().__init__()
e = Quiet(404, "not found")
print(e.args) # (404, 'not found')
print(str(e)) # (404, 'not found')The text of str(e) is therefore the whole tuple, which is rarely what a user wants to read. Calling super().__init__(text) replaces args with (text,) and produces a clean message. The exam checks whether you know which of the two outputs a given class produces.
Overriding __str__
If you prefer to keep the original arguments but control the printed text, define __str__:
class Refusal(Exception):
def __str__(self):
return "payment refused"
r = Refusal("code 51")
print(r) # payment refused
print(r.args) # ('code 51',)print and str() use the custom text, while args is unchanged.
Raising and catching custom exceptions
A custom exception follows every rule of the previous lessons:
- It matches a handler that names its class or any of its parents.
- Specific handlers must come before general ones.
- It propagates up the call stack, runs
finallyblocks on the way, and can be re-raised with a bareraise. - It can be chained with
raise NewError(...) from errto translate a low-level failure into a domain failure.
def load_price(sku, table):
try:
return table[sku]
except KeyError as err:
raise UnknownProductError(f"unknown product {sku}") from errThe caller sees a domain-specific exception, and the traceback still shows the original KeyError as the cause. Compare exception propagation and chaining to distinguish an explicit cause from a bare re-raise.
Worked example: choosing handlers for a hierarchy
Problem. Given the classes below, what does the program print?
class AppError(Exception): pass
class DataError(AppError): pass
class FormatError(DataError): pass
def check(n):
try:
if n == 1:
raise FormatError("fmt")
if n == 2:
raise DataError("data")
if n == 3:
raise AppError("app")
return "ok"
except DataError:
return "D"
except FormatError:
return "F"
except AppError:
return "A"
print(check(1), check(2), check(3), check(4))Step 1: check(1). FormatError inherits from DataError. The first clause except DataError matches because subclasses match their parents. The result is D.
Step 2: check(2). DataError matches the first clause: D.
Step 3: check(3). AppError is the parent of DataError, not a child, so it does not match the first two clauses. It matches the third: A.
Step 4: check(4). Nothing is raised: ok.
Solution. The output is D D A ok. The second clause except FormatError can never run, because its parent appears before it.
Why other answers are wrong. The answer F D A ok assumes Python searches for the most specific match, but it takes the first matching clause from top to bottom. The answer D D D ok wrongly treats AppError, the parent, as if it matched a clause that names its child DataError; matching goes from child to parent, never the other way.
A second worked example: building a validator
Problem. A registration module receives a string name and an integer age. It must accept names of 1 to 40 code points and ages from 18 through 120, rejecting values outside those ranges. Callers want one handler for all validation problems, and the web layer wants to display the field name. Design the exceptions and use them.
Step 1: define a base class. Callers want a single handler, so create ValidationError. Because the failures are wrong values, inherit from ValueError, so generic code that handles ValueError also works.
Step 2: carry the field name. Store the field in an attribute and keep a readable message.
class ValidationError(ValueError):
def __init__(self, field, message):
super().__init__(f"{field}: {message}")
self.field = field
class EmptyFieldError(ValidationError):
def __init__(self, field):
super().__init__(field, "must not be empty")
class OutOfRangeError(ValidationError):
def __init__(self, field, low, high):
super().__init__(field, f"must be between {low} and {high}")
self.low, self.high = low, highStep 3: raise them.
def validate(name, age):
if not name:
raise EmptyFieldError("name")
if len(name) > 40:
raise OutOfRangeError("name", 1, 40)
if not 18 <= age <= 120:
raise OutOfRangeError("age", 18, 120)
for data in [("", 30), ("Ada", 12), ("Ada", 36)]:
try:
validate(*data)
except ValidationError as err:
print(err.field, "->", err)
else:
print("valid")Step 4: read the output.
name -> name: must not be empty
age -> age: must be between 18 and 120
validWhy other designs are weaker. Raising plain Exception("...") forces callers to compare text. A single class can carry a field attribute, but distinct child classes also let except distinguish empty fields from out-of-range values. Inheriting from BaseException would escape except Exception handlers. Using assert is wrong because the rules concern user data and must survive the -O flag.
A tracing drill with attributes
Exam items often combine a custom __init__ with a handler that reads an attribute. Trace this one.
class LimitError(Exception):
def __init__(self, limit, used):
super().__init__(f"{used}/{limit}")
self.left = limit - used
def spend(budget, cost):
if cost > budget:
raise LimitError(budget, cost)
return budget - cost
def plan(budget, costs):
done = 0
try:
for c in costs:
budget = spend(budget, c)
done += 1
except LimitError as err:
print("stopped:", err, err.left, err.args)
finally:
print("done", done)
plan(10, [4, 3, 5, 1])- The first cost, 4, leaves a budget of 6 and
donebecomes 1. - The second cost, 3, leaves 3 and
donebecomes 2. - The third cost, 5, exceeds the remaining budget of 3, so
spendraisesLimitError(3, 5). The message is"5/3"anderr.leftis3 - 5, which is-2. - The handler prints
stopped: 5/3 -2 ('5/3',). The loop is abandoned, so the fourth cost is never examined. finallyprintsdone 2.
Two details decide such questions. First, because super().__init__ received one formatted string, args is a one-element tuple holding that string and not the numbers. Second, the attribute left was computed from the constructor arguments, so it can be negative; the exception stores whatever the class decides to store.
Where exceptions belong in a layered program
Larger programs have layers: a storage layer that talks to files or a database, a service layer with the business rules, and an interface that talks to the user. A good design translates errors at each boundary.
| Layer | Failure received | Response at this boundary |
|---|---|---|
| Storage | FileNotFoundError, KeyError |
RecordNotFoundError |
| Service | ValueError from parsing |
ValidationError |
| Interface | any ShopError |
message shown to the user |
The interface layer then needs only one handler for the package base class, plus perhaps one for a few cases that deserve a special message. It never needs to know that a dictionary or a file was involved, which makes the storage layer replaceable. Chaining with from keeps the technical cause available for logs. The interface must separately choose a suitable public message: chaining does not hide a traceback automatically.
Design guidelines
- Keep the hierarchy small. Two levels (package base plus a few specific classes) are enough in most programs.
- Put useful data in attributes, not in the message text that others must parse.
- Make the message human-readable; it ends up in logs.
- Do not use exceptions for ordinary control flow where a simple
ifwould do, but do use them for failures a caller may want to recover from. - Document each exception in the docstring of the function that raises it.
Common pitfalls and exam tips
- A class that does not inherit from an exception class cannot be raised.
class Oops: passfollowed byraise Oops()fails withTypeError: exceptions must derive from BaseException. argsin the demonstrated subclasses. Inherited construction records positional arguments;super().__init__(text)then replaces them with(text,). Inspect any custom changes before predicting output.- Order of handlers in a hierarchy. A parent class placed first hides all its children.
__str__changes the printed text only, notargs.- Multiple inheritance can match several handler families, but exception bases may have incompatible layouts. Prefer one base in application designs.
passis enough for a custom exception class; no special method is required.raise Classattempts construction without arguments. A class requiring constructor arguments fails withTypeError; pass an explicit instance instead.
Exam tip. Draw the small class tree from the code, write the class of the raised exception and list its ancestors. Then read the
exceptclauses from the top and stop at the first class that appears in the ancestor list.
Mini case study: the order service
An order service has these classes:
class OrderError(Exception): pass
class PaymentError(OrderError): pass
class CardDeclinedError(PaymentError): passThe caller is written as:
try:
process(order)
except PaymentError:
notify_support()
except CardDeclinedError:
ask_for_another_card()Customers whose card is declined are reported to support instead of being asked for another card.
Task. Explain the problem and give a corrected version that also logs any other order error.
Solution.
CardDeclinedErrorinherits fromPaymentError, so the first clause matches it. The second clause is dead code.- The specific class must come first, and a general
OrderErrorclause can follow as a safety net.
try:
process(order)
except CardDeclinedError:
ask_for_another_card()
except PaymentError:
notify_support()
except OrderError as err:
log_error(err)Now declined cards get the right treatment, other payment problems reach support, and every remaining order error is logged. Unrelated bugs, such as a TypeError, still propagate, which keeps real defects visible.
Key terms
- Custom (user-defined) exception: a class derived from
Exceptionor one of its subclasses. - Base exception of a package: a common parent for its declared domain errors, not for every possible bug.
super().__init__: call that stores the message inargs.__str__: method that controls the text shown byprint(err).- Multiple inheritance: deriving from several parents to match several handler families.
- Exception chaining: linking a domain error to its low-level cause with
from.
Summary checklist
- I can create an exception with
class Name(Exception): pass. - I know why user-defined errors must not derive from
BaseException. - I can build a package base class and specific children.
- I can add attributes and call
super().__init__. - I can predict
argsandstr()for classes with and withoutsuper().__init__. - I order handlers from the most specific class to the most general.
- I can translate low-level errors with
raise ... from.
Official sources
-
PCAP-31-03 exam syllabus, objective 2.2: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
-
Python tutorial, User-defined exceptions: https://docs.python.org/3.14/tutorial/errors.html#user-defined-exceptions (opens in a new tab)
-
Built-in exceptions: https://docs.python.org/3.14/library/exceptions.html (opens in a new tab)
-
CPython exception construction (implementation reference): https://raw.githubusercontent.com/python/cpython/3.14/Objects/exceptions.c (opens in a new tab)
