🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Python Exceptions: Chaining, Retries, and with

Python Error HandlingđŸŸĸ Free Lesson

Python Exceptions: Chaining, Retries, and with

Error handling is where a codebase's design becomes visible. Code that raises vague exceptions, catches them broadly, and returns a silent None forces every caller to guess what went wrong; code that raises specific exceptions, chains causes, and confines try blocks to the smallest statement that can fail lets a caller decide precisely what to do. The Python features that support this — custom exception classes, raise ... from, context managers, and retry helpers — are all short. The hard part is deciding which failures deserve recovery, which deserve propagation, and which should be impossible to ignore. This lesson works through those decisions with code you can lift directly.

What You'll Learn

  • 1Design an exception hierarchy that supports precise catching
  • 2Chain causes so tracebacks preserve the original failure
  • 3Write retry logic that distinguishes transient from permanent faults
  • 4Keep try blocks narrow and let context managers own cleanup

Hierarchy before messages

A good exception hierarchy answers two questions at once: what went wrong, and at what layer. Start with one base class for your application or library, then derive categories — validation, not found, conflict, unavailable — and let specific exceptions add structured fields rather than longer messages. Structured fields matter because code that catches your exception usually needs the field name or the resource id, and parsing that out of a message string is a design failure.

The hierarchy's real payoff is catch granularity. A web layer can catch the single base class to produce an error response, while a domain service catches NotFoundError to decide between retrying a lookup and returning an empty result. If every error were a bare Exception, that distinction would live in message matching. Keep the tree shallow — three or four levels is plenty — and give each class a docstring stating when it should be caught.

python
class AppError(Exception):
    """Base class for every failure this library raises."""

    def __init__(self, message, code=None):
        super().__init__(message)
        self.code = code or self.__class__.__name__

class ValidationError(AppError):
    def __init__(self, field, message):
        super().__init__(f"{field}: {message}", code="invalid_field")
        self.field = field

class NotFoundError(AppError):
    def __init__(self, resource, identifier):
        super().__init__(f"{resource} not found: {identifier}", code="not_found")
        self.resource = resource
        self.identifier = identifier

class ConflictError(AppError):
    pass

def load_user(user_id, store):
    if user_id not in store:
        raise NotFoundError("user", user_id)
    if not store[user_id].get("active", True):
        raise ConflictError("user is deactivated")
    return store[user_id]

try:
    load_user(7, {})
except ValidationError as exc:
    print("field", exc.field)
except AppError as exc:
    print("app failure", exc.code)   # not_found

Note how the second handler catches the base class and still recovers a machine-readable code. That is the intended use of the hierarchy: catch narrowly when you can act, catch broadly when you can only translate.

Chaining so the cause survives

When code converts one failure into another — wrapping a FileNotFoundError as a configuration error — the original traceback is otherwise lost, and debugging becomes archaeology. raise NewError(...) from err sets __cause__ explicitly, so the traceback prints "The above exception was the direct cause". raise NewError(...) while another exception is active sets __context__ implicitly, printed as "During handling of the above exception". Both appear in the traceback; only from states the relationship deliberately.

Use from err when you are translating a known failure into a higher-level one, and from None when the inner exception is noise the reader should not see — typically a failed probe inside a fallback that then succeeds. Chain one level of meaningful context rather than five, because a traceback that wraps every frame in a custom message hides the line that actually failed.

python
import json

def load_config(path):
    try:
        with open(path, encoding="utf-8") as handle:
            return json.load(handle)
    except FileNotFoundError as err:
        raise AppError(f"config missing at {path}", code="config_missing") from err
    except json.JSONDecodeError as err:
        raise ValidationError("config", f"invalid JSON: {err}") from err

def has_probe(label):
    try:
        raise KeyError(label)
    except KeyError:
        return False

try:
    load_config("nope.json")
except AppError as exc:
    print(exc)                      # config missing at nope.json
    print("cause:", type(exc.__cause__).__name__)   # FileNotFoundError

print(has_probe("x"))               # False — inner failure hidden on purpose

The from None idiom deserves restraint: it is correct when the caught exception is an expected control-flow signal, and wrong when it erases evidence of a real bug. If you are unsure whether a reader will need the cause, chain it — tracebacks are cheap, lost context is not.

Narrow try blocks and honest recovery

The most common structural mistake is wrapping an entire function body in one try. It works until an unrelated line raises, and the handler reports the wrong cause while the actual failure scrolls past. The rule is to place try around the specific call that can fail — often a single open, request, or parse — and to let everything else run unguarded so bugs surface as bugs.

Recovery needs its own discipline. Catch only exceptions you can handle; re-raise everything else by not catching it at all. A handler that catches Exception, logs, and continues is effectively claiming that any failure in that region is acceptable, which is rarely true. When you do catch broadly, re-raise unexpected types after adding context, and never return a fabricated default that lets corruption travel further downstream.

python
import json
import urllib.error
import urllib.request

def fetch_json(url, timeout=5):
    try:
        with urllib.request.urlopen(url, timeout=timeout) as response:
            raw = response.read()
    except TimeoutError as err:
        raise UnavailableError("upstream timeout") from err
    except urllib.error.HTTPError as err:
        if err.code == 404:
            raise NotFoundError("endpoint", url) from err
        raise AppError(f"upstream returned {err.code}") from err

    try:
        return json.loads(raw)
    except json.JSONDecodeError as err:
        raise ValidationError("response", "not JSON") from err

# Bad shape: one handler covers unrelated failure modes
def fetch_all_bad(urls):
    try:
        return [fetch_json(u) for u in urls]
    except AppError:
        return []

The bad example returns an empty list whether one URL failed or every URL failed, and the caller cannot tell which. Returning [] on total failure and a partial list on partial failure is exactly the kind of ambiguity that turns a transient outage into a silent data loss incident.

Retry only the failures that will heal

Retries are appropriate for transient faults — timeouts, connection resets, rate limits, occasional five hundred responses — and actively harmful for validation errors, authentication failures, and not-found results, which will fail identically every time. The decision is a property of the exception type, so encode it in the exception or in a small predicate rather than in a blanket except Exception around the call site.

A correct retry also needs backoff with jitter. Without delay, retries synchronise into a thundering herd that keeps the upstream down; without jitter, every client waits the same interval and collides again. Cap the attempts, cap the total delay, and log each failure with its attempt number so operators can see that recovery is being attempted rather than assumed.

python
import random
import time

class UnavailableError(AppError):
    transient = True

def retry_call(func, attempts=4, base_delay=0.2, retry_on=(UnavailableError,)):
    last_error = None
    for attempt in range(1, attempts + 1):
        try:
            return func()
        except retry_on as err:
            last_error = err
            if attempt == attempts:
                break
            delay = base_delay * (2 ** (attempt - 1))
            time.sleep(delay + random.uniform(0, delay))
            print(f"retry {attempt} after {delay:.2f}s: {err}")
    raise last_error

calls = {"n": 0}

def flaky():
    calls["n"] += 1
    if calls["n"] < 3:
        raise UnavailableError("service busy")
    return "recovered"

print(retry_call(flaky))   # two retries, then 'recovered'

Watch for idempotency: a retry after a timeout may execute work that already succeeded. Only retry operations that are safe to repeat — read queries, GET requests, upserts with a deterministic key — or add an idempotency token so the upstream can recognise a duplicate.

Cleanup belongs to context managers

Manual cleanup patterns such as resource = acquire() followed by a distant release() break the moment an exception lands between them. Context managers solve this by putting acquisition and release in __enter__ and __exit__, where the runtime guarantees __exit__ runs on the way out, including on failure. The same structure captures errors: __exit__ receives the exception type, value, and traceback, can log or translate them, and returns a truthy value only when it intends to swallow the exception.

The pattern generalises well beyond files — transactions, locks, spans, temporary directories, and subscriptions all fit. When several resources must be acquired together, contextlib.ExitStack enters them dynamically, which handles a variable number of contexts without nesting with statements to arbitrary depth.

python
from contextlib import contextmanager

class transaction:
    def __init__(self, connection):
        self.connection = connection
        self.committed = False

    def __enter__(self):
        self.connection.execute("BEGIN")
        return self

    def __exit__(self, exc_type, exc_value, tb):
        if exc_type is None:
            self.connection.execute("COMMIT")
            self.committed = True
        else:
            self.connection.execute("ROLLBACK")
        return False

class FakeConnection:
    def __init__(self):
        self.log = []
    def execute(self, statement):
        self.log.append(statement)

@contextmanager
def stage(name, log):
    log.append(f"start {name}")
    try:
        yield name
    except ValueError as err:
        log.append(f"aborted {name}: {err}")
        raise
    finally:
        log.append(f"end {name}")

conn = FakeConnection()
with transaction(conn):
    conn.execute("INSERT INTO t VALUES (1)")
print(conn.log)   # ['BEGIN', 'INSERT INTO t VALUES (1)', 'COMMIT']

audit = []
try:
    with stage("parse", audit):
        raise ValueError("bad row")
except ValueError:
    pass
print(audit)      # ['start parse', 'aborted parse: bad row', 'end parse']

The return False in __exit__ is explicit rather than necessary: returning a truthy value would suppress the exception, which is almost never what you want unless the manager is deliberately providing a fallback.

Knowing when to swallow an exception

Every except block is a claim about what the program should do when reality diverges from expectation, so it helps to name the strategies before writing them. The four that cover most situations are propagate, translate, degrade, and compensate — and choosing correctly is usually a question of which layer holds enough context to act.

StrategyWhen it fitsTypical shape
PropagateThis layer cannot fix itDo not catch, or re-raise immediately
TranslateCaller needs domain vocabularyraise DomainError(...) from err
DegradeOptional feature failed, core still worksLog, fall back to a default path
CompensateWork already happened and must be undoneRoll back, then raise or notify
RetryFault is transient and the action is idempotentBounded attempts with backoff and jitter
IgnoreFailure is expected control flowCatch a specific type, no log noise

Degrade is the dangerous one, because it is easy to apply to a failure that was not optional — a cache miss behaves differently from a failed authorisation check, and treating both as "return a default" hides security-relevant events. Log degradation at a level operators actually alert on, attach the exception with exc_info=True, and never degrade on failures you cannot classify.

Common Mistakes

Catching Exception around a whole function body

Fix: Move try to the single statement that can fail, so unrelated bugs keep their traceback

Re-raising a translated error without chaining

Fix: Use raise NewError(...) from err so the original type and traceback stay attached

Retrying validation errors, 4xx responses, or authentication failures

Fix: Classify exceptions as transient or permanent and retry only the transient class

Retrying without backoff or jitter

Fix: Exponential delay plus jitter prevents a thundering herd against a struggling upstream

Returning a fabricated default after an unexpected failure

Fix: Re-raise unexpected types; only degrade when the feature is genuinely optional

Best Practices

  • Give exceptions structured fields so callers never parse message strings
  • Keep the hierarchy shallow: one base, a few categories, specific leaves
  • Place try blocks around the smallest call that can fail
  • Emit one log line per retry with attempt number and delay, then a final failure log
  • Let context managers own every cleanup path instead of writing finally blocks

Interview Questions

Q1: Difference between raise ... from err and letting Python chain implicitly?

from err sets __cause__ and states that the new exception was raised in response to the old one. Implicit chaining sets __context__ whenever an exception is raised during handling, which shows both in the traceback but does not assert the relationship. Use from for deliberate translation and from None to hide an expected probe failure.

Q2: Which exceptions should never be retried?

Deterministic ones: validation failures, not-found results, permission errors, and schema mismatches. Retrying them wastes time and can mask a bug. Only transient classes such as timeouts, connection resets, and rate limits deserve another attempt, and only when the operation is idempotent.

Q3: What does an __exit__ method receive and what can it return?

It receives the exception type, value, and traceback — all None if no exception occurred. Returning a falsy value lets the exception propagate; returning a truthy value suppresses it, which is appropriate only when the context manager deliberately handles or replaces the failure.

Key Takeaways

  • Build a small exception hierarchy and catch narrowly where you can act
  • Chain with from so translated errors keep their original cause
  • Narrow try blocks and never let a broad catch hide the failing line
  • Retry transient, idempotent failures with exponential backoff and jitter
  • Context managers guarantee cleanup and give you a single place to translate failures
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-12

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement