Skip to content

Python Custom Exceptions and Domain Errors

Step 13 of 41

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:

  1. Define an exception class by inheriting from Exception or a more specific built-in class.
  2. Explain why custom exceptions should not inherit from BaseException directly.
  3. Add attributes and a custom __init__, and predict the effect on args and str().
  4. Build a two-level hierarchy with a common base class and catch it with one handler.
  5. Choose the right parent class so that existing handlers keep working.
  6. Combine custom exceptions with raise ... from and 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.

Python
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 items

The 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.

Python
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__:

Python
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.

Python
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):
    pass

This gives callers two levels of choice:

Python
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.

Python
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)    # 6

Observe 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.

Python
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__:

Python
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 finally blocks on the way, and can be re-raised with a bare raise.
  • It can be chained with raise NewError(...) from err to translate a low-level failure into a domain failure.
Python
def load_price(sku, table):
    try:
        return table[sku]
    except KeyError as err:
        raise UnknownProductError(f"unknown product {sku}") from err

The 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?

Python
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.

Python
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, high

Step 3: raise them.

Python
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.

Text
name -> name: must not be empty
age -> age: must be between 18 and 120
valid

Why 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.

Python
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])
  1. The first cost, 4, leaves a budget of 6 and done becomes 1.
  2. The second cost, 3, leaves 3 and done becomes 2.
  3. The third cost, 5, exceeds the remaining budget of 3, so spend raises LimitError(3, 5). The message is "5/3" and err.left is 3 - 5, which is -2.
  4. The handler prints stopped: 5/3 -2 ('5/3',). The loop is abandoned, so the fourth cost is never examined.
  5. finally prints done 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 if would 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: pass followed by raise Oops() fails with TypeError: exceptions must derive from BaseException.
  • args in 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, not args.
  • Multiple inheritance can match several handler families, but exception bases may have incompatible layouts. Prefer one base in application designs.
  • pass is enough for a custom exception class; no special method is required.
  • raise Class attempts construction without arguments. A class requiring constructor arguments fails with TypeError; 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 except clauses 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:

Python
class OrderError(Exception): pass
class PaymentError(OrderError): pass
class CardDeclinedError(PaymentError): pass

The caller is written as:

Python
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.

  1. CardDeclinedError inherits from PaymentError, so the first clause matches it. The second clause is dead code.
  2. The specific class must come first, and a general OrderError clause can follow as a safety net.
Python
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 Exception or 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 in args.
  • __str__: method that controls the text shown by print(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 args and str() for classes with and without super().__init__.
  • I order handlers from the most specific class to the most general.
  • I can translate low-level errors with raise ... from.

Official sources