有没有办法遍历一个完整的序列(我无法控制),即使它引发了异常?
例如,下面的代码不起作用,因为在引发异常之后会跟随 StopIteration。
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)
因此,此代码导致:
3.3333333333333335
5.0
10.0
division by zero
但我想获得:
3.3333333333333335
5.0
10.0
division by zero
10.0
5.0
3.3333333333333335