Sub topic 7
Handling exceptions around the yield
This chapter assumes you know try/except/finally, generators, and the basic @contextmanager pattern from the previous chapter. Here you will see what happens when the body of a with block raises, and how to write the generator so cleanup always runs.
What happens to an exception in the body
A generator-based manager is a single function that is paused at yield. When the with body raises, Python calls the generator's throw() method. That resumes the generator and raises the exception at the yield line, as if the yield expression itself had failed.
Two consequences follow:
- Code after a bare
yieldis skipped, because the exception leaves the function at that line. - Only
try,except, andfinallyblocks that wrap theyieldcan see the exception.
The bug: cleanup without try/finally
This version looks reasonable but leaks on errors:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(path):
previous = os.getcwd()
os.chdir(path)
yield path
os.chdir(previous) # skipped if the body raisesIf the body raises, os.chdir(previous) never runs and the process stays in the wrong directory. The fix is to put yield inside try and the cleanup inside finally:
import os
from contextlib import contextmanager
@contextmanager
def working_directory(path):
previous = os.getcwd()
os.chdir(path)
try:
yield path
finally:
os.chdir(previous)
try:
with working_directory("/tmp"):
raise ValueError("boom")
except ValueError:
print("cwd restored:", os.getcwd() != "/tmp")The finally block runs, then the ValueError continues to propagate to the caller.
Catching an exception inside the generator
You can use except around the yield to react to errors. What you do next decides whether the exception is suppressed:
- Re-raise with a bare
raise, and the exception propagates. - Let the generator end without re-raising, and the exception is suppressed.
from contextlib import contextmanager
@contextmanager
def transaction(log):
log.append("begin")
try:
yield
except Exception:
log.append("rollback")
raise # keep the error visible to the caller
else:
log.append("commit")
log = []
try:
with transaction(log):
raise RuntimeError("fail")
except RuntimeError:
pass
print(log) # ['begin', 'rollback']On success the else branch runs and the log ends with commit. On failure it rolls back and the error still reaches the caller.
Catch narrowly
A broad except Exception: without raise hides bugs. Compare:
from contextlib import contextmanager
@contextmanager
def ignore_missing():
try:
yield
except FileNotFoundError:
pass # intentional: only this type is suppressed
with ignore_missing():
open("no-such-file.txt")
print("still running")
with ignore_missing():
{}["key"] # KeyError is not caught, so it propagatesThe second block raises KeyError, since only FileNotFoundError is handled. This is the same idea as contextlib.suppress, which you will meet in a later chapter.
Other rules to remember
- A manager must yield exactly once. If the generator never yields, or yields a second time,
@contextmanagerraisesRuntimeError. - If the generator raises a different exception than the one thrown in, the new exception replaces it, and the original is attached as
__context__. BaseExceptiontypes such asKeyboardInterruptare also thrown into the generator. Afinallyblock handles them correctly, which is one more reason to preferfinallyoverexcept Exception.
| Generator code around `yield` | Cleanup runs on error? | Exception reaches caller? |
|---|---|---|
| Cleanup after bare `yield` | No | Yes |
| `try/finally` | Yes | Yes |
| `except ...: raise` | Yes, in the handler | Yes |
| `except ...:` without raise | Yes, in the handler | No, suppressed |
Exercise
A teammate writes a @contextmanager function that opens a connection, yields it, and then calls conn.close() on the next line with no try/finally. What happens to the connection when the with body raises, and how do you fix it?
Show answer
The exception is raised at the yield line, so conn.close() never runs and the connection leaks. Wrap the yield in try and put conn.close() in a finally block. The exception then still propagates after the connection is closed.
Exercise
In a generator-based manager you write try: yield, then except ValueError: print("bad value") with no raise. What does the caller see when the body raises ValueError?
Show answer
Nothing. The generator catches the ValueError and finishes normally, so the with statement suppresses the exception and the code after the with block runs. Add a bare raise inside the except block if the caller should still see the error.