A base exception class is a package-specific superclass for related custom exceptions. Define it by inheriting from Python’s Exception class, then derive more specific exceptions from it so users can catch all package errors when needed. section 12.5.3
class TaskierError(Exception): pass
The simplest useful base exception contains only a pass statement; the inheritance establishes the package-wide exception family. section 12.5.3
Use the pattern when designing custom exceptions for a reusable package:
- Create one package-specific exception inheriting from Exception. section 12.5.3
- Derive specific exceptions from that base class, adding arguments or overriding __str__ when a clearer diagnostic is useful. section 12.5.3
- Prefer built-in exception classes when they already express the failure; use custom classes when package-specific errors or messages help developers debug. section 12.5.4
Listing 12.16 Defining a custom exception class
class FileExtensionError(TaskierError):
def __init__(self, file_path):
super().__init__()
self.file_path = file_path
def __str__(self):
return f"The file ({self.file_path}) doesn't appear to be a
CSV file."
# In another part of our package
from pathlib import Path
def upload_file(file_path):
path = Path(file_path)
if path.suffix.lower() != ".csv":
raise FileExtensionError(file_path)
else:
print(f"Processing the file at {file_path}")
FileExtensionError demonstrates a concrete subclass: it records file_path, formats a diagnostic, and is raised when upload_file receives a non-CSV path. section 12.5.3
Catching the base class lets callers handle every custom exception from the package, while catching a specific subclass preserves targeted recovery for individual failures. In custom exception hierarchies, inherit from Exception rather than BaseException. section 12.6 section 12.5.4
