PEP 342 (Coroutines via Enhanced Generators) added a throw() method to generator objects, which allows the caller to raise an exception inside the generato
One use case is to include information about the internal state of a generator in the stack trace when an exception occurs -- information that would not otherwise be visible to the caller.
For example, say we have a generator like the following where the internal state we want is the current index number of the generator:
def gen_items():
for i, item in enumerate(["", "foo", "", "foo", "bad"]):
if not item:
continue
try:
yield item
except Exception:
raise Exception("error during index: %d" % i)
The following code is not sufficient to trigger the additional exception handling:
# Stack trace includes only: "ValueError: bad value"
for item in gen_items():
if item == "bad":
raise ValueError("bad value")
However, the following code does provide the internal state:
# Stack trace also includes: "Exception: error during index: 4"
gen = item_generator()
for item in gen:
if item == "bad":
gen.throw(ValueError, "bad value")