Sub topic 6
Building a hierarchy with a common base class
This chapter assumes you can write classes, use try, except, and raise, and call super().__init__. It shows how to organize several custom exceptions under one base class so callers can catch as much or as little as they need.
Why a hierarchy helps
Python's own exceptions form a tree. FileNotFoundError and PermissionError both inherit from OSError, so except OSError catches either one. You can give your package the same structure.
Define one base class for the whole package. Every other exception in the package inherits from it, directly or through an intermediate class. Callers then have three choices:
- Catch one specific exception to handle one specific problem.
- Catch a group of related exceptions through an intermediate class.
- Catch the base class to handle any error your package raises on purpose.
A working example
The base class has no body beyond its docstring. Its job is to be a shared name.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
class MissingSettingError(ConfigError):
"""Raised when a required setting is absent."""
class PaymentError(AppError):
"""Base class for payment failures."""
class InsufficientFundsError(PaymentError):
"""Raised when a withdrawal exceeds the available balance."""
class CardDeclinedError(PaymentError):
"""Raised when the card issuer refuses a charge."""Now the same function can be handled at different levels of detail:
def charge(amount, balance):
if amount > balance:
raise InsufficientFundsError(f"need {amount}, have {balance}")
return balance - amount
try:
charge(80, 50)
except InsufficientFundsError:
print("Ask the user to top up.")
except PaymentError:
print("Some other payment problem.")
except AppError:
print("Something else in our app failed.")Python checks except clauses from top to bottom and runs the first one that matches. The output is Ask the user to top up.
Order matters
Put specific classes before their parents. If except AppError came first, it would match every exception in the package and the later clauses would never run. Linters often flag this, but Python itself does not raise an error.
try:
charge(80, 50)
except AppError:
print("Caught by the base class.")
except InsufficientFundsError:
print("Never reached.")This prints Caught by the base class.
Choosing the shape
Keep the tree shallow. Two or three levels are usually enough. Add an intermediate class only when callers would really write except for that group. If nobody catches PaymentError as a group, it is only extra structure.
Inherit from Exception, not BaseException. BaseException also covers KeyboardInterrupt and SystemExit, which an ordinary except should not swallow.
If an error is also a kind of built-in error, you can inherit from both. This lets callers who only know the built-in still catch it.
class InvalidPortError(ConfigError, ValueError):
"""Raised when a port number is not valid."""
try:
raise InvalidPortError("port must be 1-65535")
except ValueError as exc:
print(f"Caught as ValueError: {exc}")Common errors
- Raising
AppErroritself everywhere. Callers then cannot tell problems apart. Reserve the base class for catching, and raise the specific subclasses. - Defining a base class and never catching it. If no code uses the group, remove the class.
- Placing a parent
exceptbefore its child, which hides the child handler. - Creating one exception class per function. Group by what the caller can do about the problem, not by where it occurs.
Exercise
A package defines class StorageError(Exception), class DiskFullError(StorageError), and class ReadOnlyError(StorageError). You want to handle a full disk in one way and every other storage problem in another way. Write the except clauses in the correct order, and say why the order matters.
Show answer
Use except DiskFullError: first, then except StorageError:. Python runs the first matching clause. If StorageError came first, it would also match DiskFullError, so the specific handler would never run.
Exercise
Why should a package's base exception inherit from Exception and not from BaseException?
Show answer
BaseException is also the parent of KeyboardInterrupt and SystemExit. A handler for the package's base class could then swallow a Ctrl+C or an exit request. Inheriting from Exception keeps the package's errors in the ordinary error branch of the tree.