Sub topic 6
Building a Hierarchy with a Common Base Class
This chapter assumes you can write classes, use inheritance, call super().__init__, and handle errors with try, except, and raise. It also assumes you have already defined a single custom exception by subclassing Exception. Here you will organize several exceptions into one family so that callers can choose how precisely to catch them.
Why a Package Needs One Base Class
Python's built-in exceptions form a tree. KeyError and IndexError both derive from LookupError, so except LookupError handles either one. You can give your own code the same structure.
Without a shared base class, a caller who wants to handle "anything this library raised" has two bad options:
- List every exception class by name, and update the list whenever the library adds one.
- Catch
Exception, which also swallows bugs such asTypeErrorandAttributeErrorthat have nothing to do with the library.
A single base class fixes both problems. It marks a boundary: everything inherited from it was raised deliberately by your package, and everything else is unexpected.
class AppError(Exception):
"""Base class for every error raised by this package."""The base class usually has no body. Its job is to be a name that callers can catch.
A Small Hierarchy
Add a second layer when several errors share a category that callers may want to handle together. Here is a hierarchy for a small storage-backed application.
The same tree in code:
class AppError(Exception):
"""Base class for every error raised by this package."""
class ConfigError(AppError):
"""Configuration is missing or invalid."""
class StorageError(AppError):
"""A storage operation failed."""
class RecordNotFoundError(StorageError):
"""The requested record does not exist."""
class StorageUnavailableError(StorageError):
"""The storage backend cannot be reached."""
def fetch(record_id):
if record_id == 0:
raise RecordNotFoundError(f"no record with id {record_id}")
if record_id < 0:
raise StorageUnavailableError("backend is offline")
return {"id": record_id}
for rid in (1, 0, -1):
try:
print(fetch(rid))
except RecordNotFoundError:
print("not found")
except StorageError as exc:
print(f"storage problem: {exc}")Running this prints:
{'id': 1}
not found
storage problem: backend is offlineThe caller handled the specific case, RecordNotFoundError, and treated every other storage failure the same way, without naming StorageUnavailableError. If you later add StorageTimeoutError(StorageError), this code handles it correctly with no change.
Three Levels of Catching
A hierarchy gives callers three levels of precision. They pick the level that matches what they can actually do about the problem.
| Level | Example clause | Use it when |
|---|---|---|
| Leaf | `except RecordNotFoundError` | You have a specific recovery, such as creating the missing record. |
| Category | `except StorageError` | Any storage failure gets the same response, such as retrying or showing a "try later" page. |
| Base | `except AppError` | You are at a boundary, such as a web handler or command-line entry point, and want to report any library error. |
Callers can also look at the type after catching. isinstance(exc, StorageError) and issubclass(RecordNotFoundError, AppError) both work as you would expect, and RecordNotFoundError.__mro__ lists the chain of parents:
print([cls.__name__ for cls in RecordNotFoundError.__mro__])This prints ['RecordNotFoundError', 'StorageError', 'AppError', 'Exception', 'BaseException', 'object'].
Order of `except` Clauses
Python checks except clauses from top to bottom and runs the first one that matches. A parent class matches all of its children. If you put a base class first, the clauses after it can never run.
try:
fetch(0)
except AppError:
print("generic handler")
except RecordNotFoundError:
print("never reached")Python does not warn you about this. The program prints generic handler, and the second clause is dead code. Always list the most specific class first and the most general last. Linters such as pylint report this mistake as bad-except-order, so enabling that check is worth the effort.
Choosing What to Group By
The hardest part of a hierarchy is deciding which categories to create. Group by how the caller will respond, not by where in your code the error happens.
- Good category:
StorageError. A caller who retries on any storage failure benefits from the grouping. - Weak category:
DatabaseModuleError. It only tells the caller which file the error came from, and nobody writes a differentexceptfor that.
A useful test: for each intermediate class, can you name a real except clause that would use it? If not, delete the class. Keep the tree shallow. Two levels below the base class is usually enough, and three is rare. Every extra level is another name callers have to learn and another place where a new error might be put in the wrong spot.
A second test applies to leaves. Create a leaf class when callers need to distinguish that case. If the only difference between two errors is the message, use one class and vary the text. If the difference is data, such as which field was invalid, put that data in an attribute (the next chapters cover this).
Mixing in Built-In Exceptions
Sometimes your error is also a well-known built-in kind. A bad port number in a configuration file is a ConfigError, but it is also a ValueError. You can inherit from both:
class ConfigError(AppError):
"""Configuration is missing or invalid."""
class InvalidPortError(ConfigError, ValueError):
"""The configured port is not a valid port number."""
try:
raise InvalidPortError("port must be between 1 and 65535")
except ValueError as exc:
print(f"caught as ValueError: {exc}")Code that only knows about ValueError still catches this error, and code that uses except AppError or except ConfigError catches it too. This is helpful when you are replacing a built-in exception in existing code, because old callers keep working.
Use this sparingly. It makes the hierarchy harder to read, and some built-in exceptions have their own internal layout that cannot be combined with others, in which case Python raises a TypeError when the class is defined. Mixing in ValueError, KeyError, LookupError, or RuntimeError is generally safe. Be careful with OSError and its relatives.
Keep AppError itself derived from Exception, not BaseException. BaseException is the parent of KeyboardInterrupt, SystemExit, and GeneratorExit. An except BaseException in a caller's code, or a bare except:, is supposed to be the only thing that catches those, and deriving from it makes ordinary except Exception handlers miss your errors.
Where the Base Class Lives
Put the hierarchy in one module, conventionally named exceptions.py or errors.py, and import from there:
# mypackage/errors.py
class AppError(Exception):
"""Base class for every error raised by mypackage."""
class ConfigError(AppError):
"""Configuration is missing or invalid."""Then re-export the base class from the package's top-level __init__.py so callers can write from mypackage import AppError. Name the base after the package, such as RequestsError or MyPackageError, when the library will be imported by other projects. A bare AppError or Error is fine inside an application, but two libraries that both export Error make from x import * and aliases confusing.
Treat the public classes as part of your API. Callers will write except StorageError, so moving a class to a different parent later can change which handlers catch it. Adding a new leaf is safe. Inserting a new class between two existing ones is usually safe. Changing a class's parent or removing a class breaks callers.
Wrapping Third-Party Errors at the Boundary
The base class also helps you hide implementation details. If your storage layer uses a database driver, callers should not need to import the driver's exceptions. Catch them at the boundary and re-raise your own, keeping the original as the cause:
import sqlite3
def open_store(path):
try:
return sqlite3.connect(f"file:{path}?mode=rw", uri=True)
except sqlite3.OperationalError as exc:
raise StorageUnavailableError(f"cannot open {path!r}") from excIf you later switch from SQLite to another database, except StorageError in the callers still works. The from exc part is covered in a later chapter. For now, note that it keeps the driver's original error visible in the traceback.
Common Mistakes
- Raising the base class directly.
raise AppError("something went wrong")gives callers nothing to match on except the base. Reserve the base for catching, and raise leaves or categories. - Catching the base inside the library. If your own code writes
except AppError: pass, it hides failures that callers might want to see. Catch the base at program boundaries, not in the middle of the call stack. - One class per message. Dozens of leaves that differ only in wording make the hierarchy noisy without helping any
exceptclause. - Copying built-in names. A class called
TimeoutErrororPermissionErrorin your package shadows the built-in inside any module that imports it with*. PreferServiceTimeoutErrorand similar names. - Forgetting the order of clauses. As shown above, a parent before a child silently disables the child's handler.
Summary
A common base class gives callers one name that means "an error from this package." Categories in the middle let them respond to groups of failures, and leaves let them handle exact cases. Put specific except clauses before general ones, group by how callers respond, and keep the tree shallow.
Exercise
Given the classes AppError(Exception), StorageError(AppError), and RecordNotFoundError(StorageError), what does the code below print, and how would you fix it so that "record missing" is printed?
try:
raise RecordNotFoundError("id 7")
except AppError:
print("app error")
except StorageError:
print("storage error")
except RecordNotFoundError:
print("record missing")
Show answer
It prints "app error". The first clause, except AppError, matches because RecordNotFoundError is a descendant of AppError, and Python runs the first matching clause, so the other two are unreachable. To fix it, reorder the clauses from most specific to most general: RecordNotFoundError first, then StorageError, then AppError.
Exercise
A library defines LibraryError(Exception), NetworkError(LibraryError), and ParseError(LibraryError). A caller wants to retry on any network problem but show an error message for everything else the library raises. Which except clauses should the caller write, and in what order?
Show answer
Write except NetworkError: first, with the retry logic, then except LibraryError as exc: to show the message. The specific category comes first so it is not swallowed by the base class. Any future subclass of NetworkError is retried automatically, and any other LibraryError subclass reaches the message handler.