The generator method throw() provides the ability to throw an exception inside the generator from the caller point. This can be useful if we need to end the generator once it reaches a certain value or meets a particular condition.

Using the throw() method looks like the following:

def generator(): i = 0 while True: yield i i += 1 my_generator = generator() for item in my_generator: if item == 3: my_generator.throw(ValueError, "Bad value given")

To see how the throw() method can be used in a real-world scenario, let’s practice using it some more.



We have a collection of 5,000 students.

We only want to retrieve information on the first 100 students. Use the throw() method to throw a ValueError of “Invalid student ID” if the iterated student ID goes over 100. Insert your code before the print(student_id) line.

Sign up to start coding

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?