Python › Comprehensions & Generators
How does generator.throw() let you inject an exception into a paused generator, and how would the generator handle it?
AdvancedAnswer
generator.throw(exception) resumes the generator by raising the given exception at the currently-paused yield point INSIDE the generator's frame — if the generator has a try/except around that yield, it can catch and handle it (potentially yielding a different value); otherwise, the exception propagates out to the caller of throw().
def resilient_gen():
try:
while True:
yield "working"
except ValueError:
yield "recovered from error"
gen = resilient_gen()
next(gen) # "working"
print(gen.throw(ValueError)) # "recovered from error"Real-world example Building a generator-based state machine or task runner that can gracefully handle externally-injected error conditions.