Generators can receive values with send() and handle exceptions with throw().
send() — pass values into generator:
1def accumulator():2 total = 03 while True:4 value = yield total5 if value is None:6 break7 total += value89gen = accumulator()10next(gen) # Initialize (first yield)11gen.send(10) # total = 10, yields 1012gen.send(20) # total = 30, yields 3013gen.send(5) # total = 35, yields 35
throw() — inject exceptions:
1def resilient():2 while True:3 try:4 value = yield5 print(f"Got: {value}")6 except ValueError:7 print("Invalid value, retrying")89gen = resilient()10next(gen)11gen.send("hello") # Got: hello12gen.throw(ValueError, "bad input")13# Invalid value, retrying
close() — stops generator, triggers GeneratorExit.