Sub topic 7
Handling exceptions around the yield
This chapter assumes you can write a basic @contextmanager function, as covered in the previous chapter. It also assumes you know try/except/else/finally and how generators resume after yield. Here you will learn what happens to an exception raised in a with body when the manager is a generator, and how to place try blocks so that cleanup, suppression, and translation behave as you intend.
What actually happens at the yield
A @contextmanager function is a generator. The decorator wraps it in an object with __enter__ and __exit__ methods.
__enter__runs the generator up to theyield. The yielded value becomes theastarget.- If the
withbody finishes normally,__exit__resumes the generator withnext(). The code afteryieldruns, and the generator must then finish. - If the body raises,
__exit__callsgenerator.throw(exception). The exception is raised inside the generator, at theyieldexpression.
The second and third cases are where your code decides the outcome. The yield is the point where the body's exception arrives, so a try block around the yield is what lets you react to it.
Mistake 1: no try around the yield
Consider a manager with no try block.
from contextlib import contextmanager
@contextmanager
def broken():
print("setup")
yield
print("cleanup")
try:
with broken():
raise ValueError("boom")
except ValueError as exc:
print("caught", exc)The output is:
setup
caught boomThe ValueError is thrown into the generator at yield. Nothing handles it, so it leaves the generator immediately and print("cleanup") never runs. Code written after a bare yield runs only when the body succeeds.
Pattern 1: try/finally for guaranteed cleanup
When cleanup must always happen, wrap the yield in try/finally.
from contextlib import contextmanager
@contextmanager
def reliable():
print("setup")
try:
yield
finally:
print("cleanup")
try:
with reliable():
raise ValueError("boom")
except ValueError as exc:
print("caught", exc)Now the output is setup, cleanup, caught boom. The finally block runs, and the exception continues to propagate afterward because the generator never handled it. This is the default pattern for any manager that acquires something: files, locks, directory changes, temporary settings.
Put the acquisition before the try, as working_directory does earlier in this tutorial. If acquiring fails, there is nothing to release, and a finally block would try to release something you never got.
Pattern 2: react to success and failure differently
Sometimes success and failure need different actions. A database transaction should commit on success and roll back on failure. Use except for the failure path and else for the success path.
import sqlite3
from contextlib import contextmanager
@contextmanager
def transaction(conn):
try:
yield conn
except BaseException:
conn.rollback()
raise
else:
conn.commit()
conn = sqlite3.connect(":memory:")
conn.execute("CREATE TABLE t (n INTEGER)")
conn.commit()
try:
with transaction(conn) as c:
c.execute("INSERT INTO t VALUES (1)")
raise RuntimeError("fail")
except RuntimeError:
pass
print(conn.execute("SELECT COUNT(*) FROM t").fetchone()[0])
with transaction(conn) as c:
c.execute("INSERT INTO t VALUES (2)")
print(conn.execute("SELECT COUNT(*) FROM t").fetchone()[0])This prints 0 and then 1. The first insert was rolled back, and the second was committed.
Two details matter here.
- The bare
raisere-raises the original exception. Without it, the generator would end normally and the error would be suppressed, which is almost never what you want after a rollback. - The manager catches
BaseException, notException. That way aKeyboardInterruptin the body also triggers the rollback. Because the handler re-raises, nothing is hidden.
The else branch is needed because a commit placed after the try statement is easy to confuse with the failure path. With else, the commit runs only when the body did not raise. If the commit itself fails, that error propagates normally and is not caught by the except clause above it.
Pattern 3: suppress by not re-raising
If the generator catches the exception and then returns, contextmanager treats the exception as handled. Execution continues after the with block.
from contextlib import contextmanager
@contextmanager
def ignore_missing_keys():
try:
yield
except KeyError as exc:
print(f"ignored missing key {exc}")
with ignore_missing_keys():
{}["color"]
print("not reached")
print("execution continues")The output is ignored missing key 'color' followed by execution continues. The line print("not reached") never runs. The exception ended the body at the point it was raised, and suppression only lets the program resume after the block.
Keep the suppressed type narrow. except Exception: here would hide every bug in the body. If you only need silence for one exception type, contextlib.suppress already does exactly this.
Pattern 4: translate an exception
A manager can catch a low-level exception and raise a more meaningful one. Use raise ... from to preserve the cause.
from contextlib import contextmanager
class ConfigError(Exception):
pass
@contextmanager
def config_errors(name):
try:
yield
except KeyError as exc:
raise ConfigError(f"{name}: missing key {exc}") from exc
settings = {"host": "localhost"}
try:
with config_errors("server.ini"):
port = settings["port"]
except ConfigError as err:
print(err)
print(type(err.__cause__).__name__)This prints server.ini: missing key 'port' and KeyError. Callers handle one domain-specific error type instead of a mix of KeyError, ValueError, and others.
Which pattern, and what the outcome is
| Generator structure | Cleanup on error | Exception outcome |
|---|---|---|
| Bare `yield`, code after it | Skipped | Propagates |
| `try` / `finally` | Runs | Propagates |
| `except` then bare `raise` | Runs in the handler | Propagates |
| `except` without `raise` | Runs in the handler | Suppressed |
| `except` then `raise New from exc` | Runs in the handler | Replaced by the new exception |
| `else` after the `try` | Not run on error | Not involved |
Rules the generator must follow
contextmanager checks the generator's behavior after each step and raises RuntimeError when the rules are broken.
- The generator must
yieldexactly once. If it finishes without yielding,__enter__raisesRuntimeError: generator didn't yield. - After the body ends normally, the generator must finish. A second
yieldraisesRuntimeError: generator didn't stop. - After an exception is thrown in, the generator must also finish or raise. Yielding again raises
RuntimeError: generator didn't stop after throw().
The third rule is a common slip when you try to retry from inside a manager.
from contextlib import contextmanager
@contextmanager
def twice():
try:
yield 1
except ValueError:
yield 2 # wrong: yields a second time
try:
with twice():
raise ValueError("body failed")
except RuntimeError as err:
print(err)The output is generator didn't stop after throw(). A context manager cannot rerun the body. If you need retries, write a loop around the with statement.
Subtleties worth knowing
- Identity check on re-raise. When the generator raises the same exception object it received,
contextmanagerrecognizes it and lets it propagate unchanged. When it raises a different one, the new exception propagates, and the original is attached as its__context__automatically. - Errors in
finally. If cleanup itself raises while an exception is in flight, the cleanup error replaces the original in the traceback, with the original shown as its context. Keep cleanup code simple and defensive. returnandbreakin the body. Leaving thewithblock byreturn,break, orcontinuecounts as a normal exit, so the code afteryield(includingelse) runs. Only a raised exception goes throughthrow().- The exit-time value is discarded. A
return valuein the generator afteryieldhas no effect on the caller. Share results through the yielded object instead.
Exercises
Exercise
A manager is written as @contextmanager def lock_it(lock): lock.acquire(); yield; lock.release(). A body raises an exception. What goes wrong, and how do you fix it?
Show answer
The exception is thrown into the generator at the yield and nothing handles it, so lock.release() never runs and the lock stays held. Fix it by wrapping the yield: lock.acquire() then try: yield and finally: lock.release(). Acquire before the try so a failed acquire does not trigger a release.
Exercise
You write a manager with try: yield and except ValueError: print("bad value"), with no raise. The body of a with block raises ValueError on its second line. Does the program stop, and are the lines after the failing line in the body executed?
Show answer
The program does not stop. The generator handles the exception and finishes, so contextmanager suppresses it and execution continues after the with block. The lines in the body after the failing line are never executed, because the exception already ended the body. To let the error reach the caller, add a bare raise in the handler.
Exercise
What error do you get if a generator-based manager yields a second time inside its except block, and why does contextmanager forbid it?
Show answer
You get RuntimeError: generator didn't stop after throw(). The with statement can run its body only once, so the manager cannot resume it. After an exception is thrown in, the generator must either finish, which suppresses the exception, or raise, which propagates it.