0

I want to create an Iterator that runs a couple of checks and yield an object that follows all the checks, if no object is found, it raises a StopIteration to exit loops. Something similar to the code below:

def gen():
    for i in range(3):
        yield i

    raise StopIteration("Done")

for i in gen():
    print(i)

But when I run this I get the following output:

0
1
2
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-19-56228d701618> in gen()
      4 
----> 5     raise StopIteration("Done")

StopIteration: Done

The above exception was the direct cause of the following exception:

RuntimeError                              Traceback (most recent call last)
<ipython-input-20-a753ba4ac5a8> in <module>
----> 1 for i in gen():
      2     print(i)

I later change the code to exit in a different manner but this made me curious, doesn't the for loop catch a StopIteration exception to finish the loop? Why would the code above result in such an error?

João Areias
  • 1,192
  • 11
  • 41

0 Answers0