Sub topic 13
Mistakes to Avoid
This chapter collects the errors that show up most often in custom exception code. It assumes you can already define an exception by subclassing Exception, add attributes with a custom __init__, and use raise ... from. Each section shows the mistake, explains why it hurts, and gives a fix.
Choosing the wrong base class
Application errors should derive from Exception, directly or through your own base class. Deriving from BaseException is a mistake. BaseException is the parent of KeyboardInterrupt, SystemExit, and GeneratorExit, which are signals that the program is stopping. A handler written as except Exception: does not catch these, so your error would slip past it.
class FatalAppError(BaseException):
"""Wrong: this escapes ordinary error handlers."""
try:
try:
raise FatalAppError("boom")
except Exception:
print("handled by except Exception")
except BaseException as exc:
print(f"escaped to the outer handler: {exc}")The program prints only the second message. Any retry loop, worker, or web framework that catches Exception to keep running would let this error terminate the process.
The opposite error is subclassing a built-in with an unrelated meaning. If ConfigError derives from KeyError, then except KeyError: around a dictionary lookup also catches configuration problems. You may inherit from a built-in on purpose when the new error really is a specialized version of it. For example, class ConfigError(AppError, ValueError) lets callers who only know ValueError still handle it. Do that deliberately, and never to save a few lines.
Defining exceptions you do not need
Not every failure needs a class. If a built-in already describes the problem, use it. A function that receives a negative age should raise ValueError, and a missing dictionary key is a KeyError. A custom class pays off when callers need to tell your failure apart from others, or when the error carries data.
The reverse mistake is also common. One class named MyError that is raised for every problem forces callers to read message text to find out what happened. A good test is to ask whether any caller would ever write a different except clause for this case. If not, don't create the class. If yes, create it.
Skipping a common base class
Without a shared base, callers cannot catch "anything this package raises" in one clause. They must list every class, and the list goes stale each time you add one.
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""Raised when configuration is missing or invalid."""
class StorageError(AppError):
"""Raised when the storage backend fails."""
def run():
raise StorageError("disk full")
try:
run()
except AppError as exc:
print(f"{type(exc).__name__}: {exc}")Hierarchies can also grow too deep. A chain such as AppError -> DataError -> DatabaseError -> QueryError -> SlowQueryError makes each except clause a guess about which level to use. Two or three levels are enough for most packages. Add a level only when callers will catch at that level.
Reusing names from the standard library
Python already defines TimeoutError, ConnectionError, PermissionError, FileExistsError, and others. If you write class TimeoutError(AppError) in your module, you shadow the built-in inside that module. A reader who sees except TimeoutError: cannot tell which class is meant. Code that imports your class with from yourpackage import * silently replaces the built-in as well.
Pick a distinct name instead, such as RequestTimeoutError. Also keep the Error suffix on classes that report faults. ConfigError reads as an error, while Config or BadConfig does not.
Catching too much, or too quietly
Custom exceptions let you catch narrowly, so use that ability. These patterns throw it away:
def risky():
raise ValueError("unexpected input")
# Mistake 1: the bare except also catches KeyboardInterrupt and SystemExit.
try:
risky()
except:
pass
# Mistake 2: the error disappears with no log and no re-raise.
try:
risky()
except Exception:
passA silent pass hides bugs. If you must continue after a failure, log it with logging.exception(...) or convert it into a more specific error. Catch your own base class (except AppError) when you mean "any failure from this application", and catch a specific subclass when you can recover from that one case.
An overly broad try block causes a related problem. If twenty lines sit inside try and only one of them can raise ConfigError, a ConfigError raised by another line is handled as if the first line failed. Keep the try body to the statement that can raise.
Losing the original cause
When you translate a low-level error into an application error, keep the original. Otherwise the traceback shows only your new message, and the real reason is gone.
class ConfigError(Exception):
"""Raised when configuration is missing or invalid."""
def load_port_bad(raw):
try:
return int(raw)
except ValueError:
# Implicit chaining only: the traceback says "During handling of
# the above exception, another exception occurred".
raise ConfigError(f"invalid port: {raw!r}")
def load_port(raw):
try:
return int(raw)
except ValueError as exc:
# Explicit chaining: the traceback says "The above exception was
# the direct cause of the following exception".
raise ConfigError(f"invalid port: {raw!r}") from excIn both versions Python records the original error in __context__. Only from exc sets __cause__, and it changes the traceback wording to say the first error directly caused the second. That wording tells a reader the translation was intentional rather than a bug inside the handler.
The reverse mistake is raise ... from None used by habit. It sets __suppress_context__ and hides the original error from the traceback. That is appropriate when the low-level error is noise, for example a KeyError that only means "not found" and your own message says the same thing more clearly. Do not use it when the hidden error could help someone debug.
Breaking `args` and pickling
This is the least visible mistake. BaseException.__reduce__ rebuilds an exception from its class and its args tuple, calling cls(*args). Pickling and copying use it. Libraries that send exceptions between processes, such as multiprocessing and concurrent.futures.ProcessPoolExecutor, depend on pickling too. If your __init__ takes two parameters but passes a single formatted string to super().__init__, then args holds one item and reconstruction fails.
import pickle
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
def __init__(self, balance, amount):
super().__init__(f"Cannot withdraw {amount}; balance is {balance}")
self.balance = balance
self.amount = amount
err = InsufficientFundsError(balance=50, amount=80)
try:
pickle.loads(pickle.dumps(err))
except TypeError as exc:
print(f"unpickling failed: {exc}")The error occurs on loading, not on dumping. A worker process may raise it long after the class was written, and the parent then sees a confusing TypeError rather than your exception.
The fix is to pass the same arguments that __init__ receives to super().__init__, and build the message in __str__:
import copy
import pickle
class InsufficientFundsError(Exception):
"""Raised when a withdrawal exceeds the available balance."""
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}"
err = InsufficientFundsError(balance=50, amount=80)
restored = pickle.loads(pickle.dumps(err))
print(restored.balance, restored.amount)
print(restored)
print(copy.copy(err).amount)Keyword-only parameters need extra care. cls(*args) cannot supply them, so an exception whose __init__ uses *, balance, amount cannot be rebuilt this way. Give such exceptions positional parameters, or define __reduce__ yourself.
Putting data only in the message
If the only record of a value is inside the message string, callers must parse text to use it. That code breaks when you reword the message.
class RateLimitError(Exception):
"""Raised when the server asks the client to slow down."""
def __init__(self, retry_after):
super().__init__(retry_after)
self.retry_after = retry_after
def __str__(self):
return f"Rate limited; retry after {self.retry_after} seconds"
def wait_time(exc):
# Mistake: int(str(exc).split()[-2]) breaks when the wording changes.
return exc.retry_after
try:
raise RateLimitError(30)
except RateLimitError as exc:
print(wait_time(exc))Store facts as attributes, and treat the message as text for humans. Tests should check attributes in the same way.
Putting secrets in messages
Exception messages end up in logs, error trackers, and sometimes in responses shown to users. A message such as f"login failed for {user} with password {password}" leaks a credential to every place that records the traceback. Include identifiers that help debugging, such as a user name or request ID, and leave out passwords, tokens, and full connection strings.
Mistakes at a glance
| Mistake | Effect | Fix |
|---|---|---|
| Deriving from `BaseException` | Escapes `except Exception` handlers | Derive from `Exception` or your own base |
| One generic `MyError` for everything | Callers parse message text | Add classes only where callers branch |
| No package base class | Callers list every class | Define one `AppError` base |
| Reusing built-in names | Shadowing and confusion | Choose distinct names ending in `Error` |
| Bare `except:` or silent `pass` | Hidden bugs | Catch narrowly, log or re-raise |
| Missing `from exc` | Cause not marked in traceback | Use `raise ... from exc` |
| `__init__` args not passed to `super()` | Pickle and copy fail | Pass same args, define `__str__` |
| Data only in the message | Fragile text parsing | Store attributes |
| Secrets in messages | Leaks to logs | Leave them out |
Testing for these mistakes
Several of these mistakes are easy to guard with tests. A round trip through pickle catches argument mismatches, and pytest.raises confirms the cause was kept.
import pickle
import pytest
class AppError(Exception):
"""Base class for errors raised by this application."""
class ConfigError(AppError):
"""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 exc
def test_config_error_keeps_cause():
with pytest.raises(AppError, match="invalid port") as info:
load_port("abc")
assert isinstance(info.value.__cause__, ValueError)
def test_config_error_survives_pickle():
original = ConfigError("bad value")
restored = pickle.loads(pickle.dumps(original))
assert type(restored) is ConfigError
assert restored.args == original.argsExercise
A worker process raises QuotaError, but the parent process fails with TypeError: __init__() missing 1 required positional argument: 'limit'. The class defines __init__(self, used, limit) and calls super().__init__(f"{used} of {limit} used"). What is wrong, and how do you fix it?
Show answer
args holds only the formatted string, so pickle calls QuotaError("...") with one argument and limit is missing. Call super().__init__(used, limit), store self.used and self.limit, and build the text in __str__. A pickle.loads(pickle.dumps(...)) round trip then works.
Exercise
A function catches KeyError from a settings lookup and raises ConfigError("missing 'database_url'") with no from clause. The team lead says to add from None so the traceback is shorter. Is that a good change? What would you write instead?
Show answer
Usually no. from None hides the original KeyError, which may name the exact key or code path that failed. Write except KeyError as exc: raise ConfigError("missing 'database_url'") from exc. Use from None only when the original error adds nothing beyond what your message already says.