本文介绍了在python中的迭代器/生成器中引发异常后继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在迭代器/生成器抛出异常之后,Python中是否有任何方法可以继续迭代?就像下面的代码一样,有什么方法可以跳过ZeroDivisionError并继续循环遍历 gener()
而无需修改 run()
Is there any way in Python to continue iterating after exception throwed by iterator/generator? Like in code below, is there any way to skip ZeroDivisionError and continue looping through gener()
without modyfying run()
function?
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?'
推荐答案
try / except
的逻辑位置将是进行违规计算的位置:
The logical place for the try/except
would be the place where the offending calculation takes place:
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
这篇关于在python中的迭代器/生成器中引发异常后继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!