Skip to content
Silver 5 min read · OOP 3 practice problems ↓

Exceptions and context managers

Things go wrong in data code: a file is missing, a row will not parse, a connection drops. Exceptions let you decide what happens then, and context managers make sure files and connections are closed whatever happens. This lesson shows both, and when each block of a try statement runs.

Foundations · Python for data engineers · Silver · Classes and robust code, lesson 2 of 2

Read first: Classes, properties and dataclasses (skip if you know it)

In plain words first

Think of cooking with a recipe. You try a step; if the milk has gone off (an exception), you have a plan B; if all went well, you serve; and whatever happened, you turn the stove off at the end.

Those are the four blocks of try: try, except, else and finally. A context manager (with) is a stove that turns itself off when you leave the kitchen, so you cannot forget.

The four blocks of try

BlockRuns when
tryAlways; the code that may fail
except EAn exception of type E (or a subclass) was raised in try
elsetry finished without an exception
finallyAlways, last: after success, after a handled error, and while an unhandled one propagates

Catch the narrowest exception you can handle, and keep the try block small so you do not catch errors from lines you did not mean to protect. finally is for clean-up that must happen no matter what.

Custom exceptions and re-raising

A small exception hierarchy lets callers react to kinds of failure: class PaymentDeclined(Exception). A bare raise inside except re-raises the current exception with its original traceback; raise New(...) from e wraps it while keeping the cause.

Python · handle one kind, let others through
class PaymentDeclined(Exception):
    pass


def charge(amount):
    if amount > 500:
        raise PaymentDeclined(f"{amount} is over the limit")
    if amount <= 0:
        raise ValueError("amount must be positive")
    return "ok"


for amount in (120, 900):
    try:
        status = charge(amount)
    except PaymentDeclined as e:
        status = f"declined: {e}"
    print(amount, status)

try:
    charge(-1)
except ValueError as e:
    print("bug in caller:", e)

Output from a real run

120 ok
900 declined: 900 is over the limit
bug in caller: amount must be positive

Context managers

with pairs setup with guaranteed clean-up: files closed, locks released, transactions committed or rolled back. Python calls __enter__ on entry (its return value is what as binds) and __exit__(exc_type, exc_value, traceback) on the way out, with the exception details if the block failed. Returning a true value from __exit__ suppresses the exception, which is almost never what you want.

Python · a context manager that records how a block ended
class Step:
    def __init__(self, name, log):
        self.name, self.log = name, log

    def __enter__(self):
        self.log.append(f"start {self.name}")
        return self

    def __exit__(self, exc_type, exc_value, traceback):
        outcome = "ok" if exc_type is None else f"failed ({exc_type.__name__})"
        self.log.append(f"end {self.name}: {outcome}")
        return False


log = []
with Step("load", log):
    pass
try:
    with Step("publish", log):
        raise TimeoutError("api down")
except TimeoutError:
    pass
print(log)

Output from a real run

['start load', 'end load: ok', 'start publish', 'end publish: failed (TimeoutError)']

contextlib.contextmanager

For simple cases, a generatorgenerator: A function that uses yield. Calling it does not run it: it returns an iterator that runs the function bit by bit, one item per next(). Learn more → decorated with @contextmanager is shorter: the code before yield is the setup, the yielded value is what as binds, and a try/finally around the yield is the clean-up.

Python · temporarily change a setting
from contextlib import contextmanager

config = {"surge": 1.0}


@contextmanager
def surge(value):
    old = config["surge"]
    config["surge"] = value
    try:
        yield config
    finally:
        config["surge"] = old


with surge(1.8) as c:
    print("inside:", c["surge"])
print("after:", config["surge"])

Output from a real run

inside: 1.8
after: 1.0

Logging instead of print

logging gives every message a level (DEBUG, INFO, WARNING, ERROR, CRITICAL) and a logger name; the setup decides which levels are shown and where. Configure it once at the start; in each module use logging.getLogger(__name__). Inside except, log.exception(...) logs at ERROR and adds the traceback.

Python · one logger, three levels shown, one hidden
import logging
import sys

logging.basicConfig(
    stream=sys.stdout,
    level=logging.INFO,
    format="%(levelname)s %(name)s: %(message)s",
    force=True,
)
log = logging.getLogger("orders.load")

log.debug("row details: hidden, because the level is INFO")
log.info("loaded %d rows from %s", 1200, "orders.csv")
log.warning("skipped %d rows with no city", 3)
try:
    rate = 1200 / 0
except ZeroDivisionError as e:
    log.error("rate calculation failed: %s", e)

Output from a real run

INFO orders.load: loaded 1200 rows from orders.csv
WARNING orders.load: skipped 3 rows with no city
ERROR orders.load: rate calculation failed: division by zero

Common mistakes

  • except Exception: pass — Hides bugs and failed writes. Catch what you can handle, log, re-raise the rest.
  • Returning True from __exit__ by accident — The exception disappears. Return False (or None).
  • Clean-up after the risky call instead of in finally — It is skipped when the call raises.

Key takeaways

  • else runs on success; finally runs always.
  • Catch narrow exceptions; re-raise with a bare raise.
  • __exit__ always runs and gets the exception; return False to let it propagate.
  • @contextmanager: setup, yield, finally.
  • Log with levels and logger names, configured once; log.exception adds the traceback.

Interview prep

THE QUESTION

"How does a with statement guarantee clean-up?"

with calls __enter__ before the block and always calls __exit__ after it, whether the block finished, returned early or raised. __exit__ receives the exception type, value and traceback (or None), so it can commit on success and roll back on failure, and its return value decides whether the exception is suppressed; normally it returns False so the error still reaches the caller. contextlib.contextmanager builds the same thing from a generator with try/finally around the yield.

Avoid: "I wrap everything in try/except Exception so the pipeline never crashes". It hides failures and corrupt writes; a crash is often the safer outcome.

Follow-ups · answer out loud, then open

Follow-up"What is the difference between raise and raise X from e?"
A bare raise re-raises the current exception unchanged, with its traceback. raise X from e raises a new exception and records e as its cause, so the traceback shows both: useful to translate a low-level error into a domain error without losing the original.
Scenario"Write to a warehouse table so that a failure half-way leaves nothing behind."
A transaction context manager: begin on enter; on exit commit if the block succeeded, roll back if it raised, and roll back too if the commit itself fails, then let the exception propagate. For object storage, write to a temporary location and rename or commit atomically at the end.
Trap"finally does not run if the try block returns."
It always runs, including after return, break or an exception. A return inside finally even overrides the earlier return, so avoid returning there.

Check yourself

3 questions

When does an else block after try run?

Show the answer

When no exception was raised in try. else is the success path.

__exit__ returns True. What happens to an exception from the block?

Show the answer

It is suppressed. A true return value suppresses it.

In a @contextmanager generator, where does clean-up go?

Show the answer

In finally around the yield. So it runs even when the block raises.

Practise this

Problems that use this, graded on hidden tests

Keep going

Up next · new module: Wrangling · 5 min read
Wrangling data without pandas
Parse, flatten, deduplicate, join and aggregate in plain Python, with SQL's null rules.

Related lessons

Previous: Classes, properties and dataclasses

Primary sources: Errors and exceptions · contextlib · Logging HOWTO