0

Is there a way to iterate over a complete sequence (that I do not control), even if it raises an exception?

For example, the following code does not work because after an exception is raised a StopIteration follows.

def do(gen):
    it = iter(gen)
    while True:
        try:
            print(next(it))
        except StopIteration:
            break
        except Exception as ex:
            print(ex)

# This is something provided by the user
# For example this:
not_my_gen = (10/x for x in [3, 2, 1, 0, 1, 2, 3])

do(not_my_gen)

Therefore this code results in:

3.3333333333333335
5.0
10.0
division by zero

but I would like to obtain:

3.3333333333333335
5.0
10.0
division by zero
10.0
5.0
3.3333333333333335
Hernan
  • 5,811
  • 10
  • 51
  • 86
  • @user56700 thanks for the suggestion, but that will not change the result – Hernan Feb 21 '22 at 18:03
  • 1
    the exception is being thrown in the generator expression. You can't continue that after the exception — it will just keep raising StopIteration. You will need to make your own generator. [Check out this thread](https://stackoverflow.com/questions/11366064/handle-an-exception-thrown-in-a-generator) – Mark Feb 21 '22 at 18:04

0 Answers0