Learn

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:

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.

Instructions

1.

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

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?