Exception Hierarchies, Retries, and Error Recovery
Error handling is where a program's design becomes visible. Code that works on the happy
path can be written by anyone; what separates a system you can operate at three in the
morning is whether failures arrive as named, catchable, self-describing events or as a
bare Exception: something went wrong with a stack trace pointing at line 402 of a file
nobody has opened in a year. Python gives you the machinery â inheritance, chaining,
except ... as, context managers â but the discipline of deciding what can go wrong and
who is responsible for each failure has to come from you.
This lesson treats exceptions as part of your public API: how to shape a hierarchy that callers can catch meaningfully, how to attach the context that makes debugging short, when retrying helps and when it makes an outage worse, and how to fall back without hiding the truth.
A hierarchy callers can catch on purpose
The purpose of an exception hierarchy is to let callers handle categories of failure
without enumerating every possible error. A single base class for your application, with
subclasses for the situations a caller might reasonably recover from, means upstream code
can write one except AppError for "log and alert" while a request handler writes a
narrower except ValidationError for "return 400". Structure should reflect how callers
want to react, not the internal module layout of where the error was raised.
class AppError(Exception):
"""Base class for every failure this application raises deliberately."""
class ValidationError(AppError):
"""Caller supplied something we refuse to process."""
def __init__(self, field, message):
self.field = field
self.message = message
super().__init__(f"{field}: {message}")
class NotFoundError(AppError):
"""The referenced resource does not exist."""
def __init__(self, resource, identifier):
self.resource = resource
self.identifier = identifier
super().__init__(f"{resource} {identifier!r} not found")
class TransientError(AppError):
"""Recovering is plausible â retrying later may succeed."""
class DependencyUnavailable(TransientError):
"""An upstream service failed in a way that may self-heal."""
Two properties make this useful in practice. First, everything derives from AppError,
so a top-level handler can catch the whole family without a brittle list. Second,
TransientError exists purely as a policy marker: retry loops key off it, and nothing
else. Raising TransientError is a statement that "trying again is a reasonable
response", which is a much better contract than a retry loop pattern-matching on message
text.
Attaching the context that makes debugging short
An exception message is read under time pressure by someone who does not have your context. Include the identifiers involved, the operation attempted, and the values that were rejected â and use chaining so the causal chain is preserved rather than replaced.
def reserve(seat_id: str, user_id: str) -> Reservation:
try:
seat = seat_store.get(seat_id)
except KeyError as exc:
raise NotFoundError("seat", seat_id) from exc
if seat.taken:
raise ValidationError("seat", f"{seat_id} is already reserved")
try:
payment_charge(user_id, seat.price)
except GatewayTimeout as exc:
raise DependencyUnavailable(
f"payment gateway timed out for user {user_id}"
) from exc
return seat_store.mark_taken(seat_id)
The from exc clause matters: without it, the original traceback â the one containing the
actual failing line inside the gateway client â is discarded, and you are left guessing.
Chain deliberately at every layer boundary, and never let an exception escape carrying a
message that only restates its type.
Retry with backoff, bounded by a policy
Retrying is correct only for failures that are transient and idempotent. A timeout on a payment capture is not safe to repeat blindly; a timeout on a read-only fetch is. Decide which of your calls are safe to replay, cap the attempts, and grow the delay â a fixed one-second retry against a struggling service is just a slower way to hammer it.
import random
import time
from functools import wraps
def retry(max_attempts=3, base_delay=0.5, cap=8.0, jitter=True):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
delay = base_delay
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except TransientError:
if attempt == max_attempts:
raise
sleep_for = delay + (random.uniform(0, delay / 2) if jitter else 0)
time.sleep(min(sleep_for, cap))
delay *= 2
return wrapper
return decorator
@retry(max_attempts=4)
def fetch_catalog():
try:
return http_get("/catalog", timeout=5)
except requests.Timeout as exc:
raise DependencyUnavailable("catalog endpoint timed out") from exc
Jitter â the random component â prevents a fleet of workers from retrying in lockstep and recreating the thundering herd that took the dependency down in the first place. If every client waits exactly two seconds, they all arrive together again at second four.
Circuit breakers: failing fast once the outage is clear
Retries help a service recover from a blip; they hurt when the service is already down, because each caller keeps waiting through a full backoff sequence while requests pile up. A circuit breaker watches the failure rate and, once a threshold is crossed, stops calling the dependency at all for a cool-down period, returning a fast failure instead.
import time
class CircuitBreaker:
def __init__(self, failure_threshold=5, reset_after=30.0):
self.failure_threshold = failure_threshold
self.reset_after = reset_after
self.failures = 0
self.open_until = 0.0
def call(self, func, *args, **kwargs):
now = time.monotonic()
if self.open_until and now < self.open_until:
raise DependencyUnavailable("circuit open â dependency recently failing")
if self.open_until and now >= self.open_until:
self.failures = 0 # half-open: allow one probe through
self.open_until = 0.0
try:
result = func(*args, **kwargs)
except TransientError:
self.failures += 1
if self.failures >= self.failure_threshold:
self.open_until = now + self.reset_after
raise
else:
self.failures = 0
return result
The single probe after the cool-down is what lets the breaker close again without manual intervention. Once that probe succeeds, normal traffic resumes; if it fails, the cool-down restarts and callers keep getting their fast failure.
Degrading instead of failing outright
Not every dependency deserves a hard stop. Recommendations can fall back to a static popular list, a search box can return recent queries when the index is unreachable, and a profile page can omit the avatar rather than 500. The rule is that the degraded path must be explicit and observable â a fallback the operator cannot see is indistinguishable from silent data loss.
| Failure | Sensible recovery | Poor recovery |
|---|---|---|
| Read-only cache miss | Recompute or fetch upstream | Raise to the user |
| Payments gateway timeout | Raise TransientError, alert a human | Retry blindly forever |
| Malformed row in an import | Skip row, count it, report at the end | Abort the whole import |
| Invalid user input | Raise ValidationError, return field-level message | Swallow and continue |
| Configuration missing at startup | Refuse to boot with a clear message | Fall back to insecure defaults |
| Rendering a widget dependency | Serve page without the widget | Block the whole response |
def recommendations_for(user_id: str) -> list[dict]:
try:
return ranker.recommend(user_id, limit=10)
except DependencyUnavailable as exc:
metrics.incr("recommendations.fallback")
log.warning("falling back for %s: %s", user_id, exc)
return catalogue.popular(limit=10)
Note the metric and the log line. A fallback that increments a counter can be alerted on; a fallback that quietly returns plausible data is how you discover stale numbers three weeks later.
Errors worth letting through
Some exceptions should propagate untouched. KeyboardInterrupt and SystemExit exist to
stop the process, GeneratorExit is part of the generator protocol, and a MemoryError
rarely improves after being caught and reraised as something friendlier. Bare
except: â which catches even those â is the classic way to turn a clean shutdown into a
hang; catch Exception or, better, your own hierarchy, and let the rest escape.
Equally important is refusing to catch what you cannot handle. If your layer has no
recovery strategy and no additional context to add, re-raise rather than logging and
swallowing. An exception that reaches the top level is a bug report; an exception that
disappears into an empty except block is a future outage.
The corollary is to catch as narrowly as the recovery you intend. A handler written as
except AppError will keep working when someone later subclasses that base for a new
error type â which is exactly the behaviour you want â while a handler written as
except KeyError around a block that also indexes two other dictionaries will quietly
mis-handle a genuine typo as a "missing record". Give the failing operation its own small
try block so the exception's origin is never in doubt.
Common Mistakes
Catching bare Exception and continuing as if nothing happened
Fix: Catch your own hierarchy, add context, and re-raise anything you cannot recover from
Retrying non-idempotent operations such as payment capture
Fix: Only retry operations that are safe to replay; treat the rest as permanent failures
Fixed retry intervals that synchronise every client
Fix: Exponential backoff with jitter, capped at a sane maximum
Raising a new exception and losing the original traceback
Fix: Use 'raise ... from exc' so the causal chain survives
Falling back silently and returning stale or generic data
Fix: Emit a metric and a log line on every fallback so degradation is visible
Best Practices
- Design exception subclasses around how callers will react, not around where the error was raised
- Include identifiers, attempted operation, and rejected values in every message
- Mark retryable failures with a dedicated base class and key retry logic off that class alone
- Fail fast once a dependency's failure rate proves an outage is under way
- Assert your error paths with tests â they are the code that runs during incidents
Key Takeaways
- An exception hierarchy is a contract: one base for logging, narrow subclasses for recovery
- Chaining with 'from' preserves the traceback you will need at three in the morning
- Retry only transient, idempotent failures, with exponential backoff and jitter
- Circuit breakers convert a slow timeout storm into an instant, honest failure
- Fallbacks must be observable â pair every degradation with a metric