The Throw() Method Of Generator Iterator


  • The throw() method enables raising an exception into a generator function from the calling code.

  • With the throw() method, a response can be given back to the generator function from the caller, thus controlling the behaviour of the generator on certain (which are deemed exceptional by the calling code of the generator) conditions.


# Example Python program that throws an exception
# into a generator function

# Define OddError
class OddError(ValueError):

# Define a generator function
def produce():
    x = 10
        while x > 0:
            x = x - 2
            x = yield x
    except ValueError:
        yield produce()

# Define a consumer that makes use of generator function
def f1(producer, val):
    x = producer.send(val)
    # Throw if the generator behaves unexpected    
    if x % 2 != 0:
        f = producer.throw(OddError)
        # Reset the generator
        print("After generator reset:")

# Value to send to the generator
toSend = 7

# Create a generator iterator
producer = produce()

# Start the generator

# Use the generator further through f1
f1(producer, toSend)



After generator reset:



Copyright 2022 ©