Sub topic 13
Mistakes to avoid
This chapter assumes you can write a custom exception class, raise and catch it, add attributes with a custom __init__, and chain with raise ... from. Here are the most common design mistakes and how to fix each one.
Inheriting from the wrong class
Subclass Exception, not BaseException. BaseException is the parent of KeyboardInterrupt, SystemExit, and GeneratorExit. Python expects those to pass through ordinary error handling. A custom exception placed beside them is skipped by except Exception, so it escapes handlers that should have caught it.
Do not subclass a built-in such as ValueError just to get a familiar name. Do it only when your error really is a specialized version of that built-in, and callers might reasonably catch the built-in.
Defining too many classes, or too few
Avoid one class per message. If callers never need to handle two errors differently, they do not need two classes. Put the difference in an attribute or in the message.
The opposite mistake is raising Exception("something failed") everywhere. Callers then have to catch every Exception, which also hides unrelated bugs.
A good test is whether a caller would write a separate except clause for the new class. If not, use a built-in exception or an existing class from your hierarchy.
Breaking `args` and pickling
If your __init__ takes extra arguments but passes only a formatted message to super().__init__, then args no longer matches the constructor signature. Pickle, copy, and multiprocessing rebuild the exception by calling the class with args. The rebuild then fails:
import pickle
class BadFundsError(Exception):
def __init__(self, balance, amount):
super().__init__(f"Cannot withdraw {amount}; balance is {balance}")
self.balance = balance
self.amount = amount
try:
pickle.loads(pickle.dumps(BadFundsError(50, 80)))
except TypeError as exc:
print(f"TypeError: {exc}")The fix is to pass the same arguments that __init__ receives to super().__init__, then build the message in __str__:
class FundsError(Exception):
def __init__(self, balance, amount):
super().__init__(balance, amount)
self.balance = balance
self.amount = amount
def __str__(self):
return f"Cannot withdraw {self.amount}; balance is {self.balance}"This matters most when exceptions cross process boundaries, for example in a worker pool.
Making callers parse messages
If the only way to learn the amount is str(exc).split(), a wording change breaks every caller. Store data as attributes and treat the message as text for people.
Hiding errors
Three habits cause most silent failures:
- A bare
except:catchesKeyboardInterruptandSystemExittoo. except Exception: passhides real bugs.raise NewError("failed")inside anexceptblock, withoutfrom exc, relies on implicit chaining. The traceback then says "During handling of the above exception, another exception occurred", which suggests a second bug and not a deliberate translation.
Use raise ... from exc when you translate an error. Use from None only when the original is noise and you have a good reason to suppress it.
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
raise ConfigError(f"invalid port: {raw!r}") from excSkipping the common base class
If a package defines ParseError, FetchError, and StoreError with no shared parent, users must list all three in every handler. A new error added later also escapes their handlers. Give the package one base class, such as AppError, and derive the rest from it.
Keep the tree shallow. Two or three levels are usually enough. Deep trees are hard to remember and rarely match how callers handle errors.
Quick checklist
| Check | Why |
|---|---|
| Derives from `Exception` or your package base | Normal handlers can catch it |
| Callers can tell it apart from other errors | The class earns its place |
| `args` matches the `__init__` signature | Pickle and copy work |
| Data is in attributes, not only in text | Callers do not parse messages |
| Translations use `raise ... from exc` | The cause stays visible |
Exercise
A teammate writes class QuotaError(Exception) with __init__(self, used, limit) that calls super().__init__(f"{used}/{limit} used"). Sending it from a worker process with multiprocessing raises a TypeError when the parent receives it. What is the cause and the fix?
Show answer
args holds only the formatted string, so unpickling calls QuotaError("5/3 used") and the required limit argument is missing. Call super().__init__(used, limit), store used and limit as attributes, and build the message in __str__.