The throw() method of generator iterator

The throw() method of the generator iterator raises an Exception into a generator function.

Yield Updated 19 Apr 2022 1 min read

Overview

  • 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
# Example Python program that throws an exception

            # into a generator function

# Define OddError

            class OddError(ValueError):

                pass

# Define a generator function

            def produce():

                x = 10

                try:

                    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:")

                    print(f.send(None))

# Value to send to the generator

            toSend = 7

# Create a generator iterator

            producer = produce()

# Start the generator

            print(producer.send(None))

# Use the generator further through f1

            f1(producer, toSend)

Output

Output
8

After generator reset:

8