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.
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