在迭代器/生成器抛出的异常之后,Python中有没有办法继续迭代?就像下面的代码一样,有没有办法跳过ZeroDivisionError并继续循环gener()
而没有modyfying run()
函数?
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
yield 2/i
def run():
for i in gener():
print i
#---- run script ----#
try:
run()
except ZeroDivisionError:
print 'what magick should i put here?'
答案 0 :(得分:9)
try/except
的合理位置将是违规计算发生的地方:
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
try:
yield 2/i
except ZeroDivisionError:
pass
答案 1 :(得分:2)
一种可能的解决方案是将问题代码包装到try ... except block:
def gener():
a = [1,2,3,4,0, 5, 6,7, 8, 0, 9]
for i in a:
try:
div_result = 2/i
except ZeroDivisionError:
div_result = None
yield div_result
答案 2 :(得分:1)
我不确定,但如果你想了解发生错误的地方,也许这更适合你:
In [1]: def gener():
...: a = [1, 2, 0, 3, 4, 5, 6, 7, 8, 9]
...: errors = []
...: for idx, i in enumerate(a):
...: try:
...: yield 2 / i
...: except ZeroDivisionError:
...: errors.append('ZeroDivisionError occured at idx = {}'.for
...: mat(idx))
...: if errors:
...: raise RuntimeWarning('\n'.join(errors))
...: