我碰到一种情况,我需要在我的try/except
代码中确定哪个嵌套发生器正在引发异常。我该怎么做?以下是一个虚拟示例:如何确定哪个嵌套的生成器产生StopIteration异常?
def genOne(iMax, jMax):
i = 0;
g2 = genTwo(jMax)
while i <= iMax:
print('genOne: ' + str(i))
next(g2)
yield
i = i + 1
def genTwo(jMax):
j = 0;
while j <= jMax:
print('genTwo: ' + str(j))
yield
j = j + 1
g1 = genOne(6, 3) # The inputs are arbitrary numbers
try:
while True:
next(g1)
except:
# Do some processing depending on who generates the StopIteration exception
谢谢!
你为什么没有'genOne'处理异常? – Blender
在真正的问题中,我无法访问生成器。假设发电机不能修改,我可以轻易确定吗? – kaosad