Skip to content
Home » The throw Method on Generators

The throw Method on Generators

Spread the love

Today we’ll see how to use the throw method on generators.

throw Method

If you haven’t read my previous two articles on generators (about the basics of generators and sending objects to generators), it’s definitely recommended to do so before you go on with this one.

And now let’s have a look at the code from my previous article again:

>>> def letter_generator(text):
...     position = 0
...     while True:
...         message = yield text[position]
...         if message!= None:
...             position = message
...         else:
...             position += 1

This generator yields the letters making up text. Suppose, we need to know the value of position as well. The generator object can use the throw method to get this information.

How does the throw method work? It raises an exception at the point where the generator’s execution was stopped and returns the next value yielded by the generator or, if the generator doesn’t yield any value, it raises the StopIteration exception. The exception passed as an argument to throw must be handled in the generator function or else it will propagate to the caller. Now let’s rewrite the code above so that it can handle the exception and so that the value of position is available. The generator is now saved in a file called generators.py. We use the try and except keywords to handle exceptions:

def letter_generator(text):
    position = 0
    while True:
        try:
            message = yield text[position]
        except Exception:
            print("position = " + str(position))
        if message!= None:
            position = message
        else:
            position += 1

Now let’s work in interactive mode. Let’s import the generator we need:

>>> from generators import letter_generator

Now let’s create the generator object:

>>> letters = letter_generator("abcdefghijklmnopqrstucwxyz")

The iterator is ready to work:

>>> next(letters)
'a'
>>> next(letters)
'b'

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

Now let’s use the throw method on the iterator. This way we’ll be informed about the current value of position. Also, the next element will be returned:

>>> letters.throw(Exception)
position = 1
'c'

Let’s use next again:

>>> next(letters)
'd'

And finally let’s use throw again. Now the value of position is different:

>>> letters.throw(Exception)
position = 3
'e'

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

Here’s the video version of the article:


Spread the love

Leave a Reply