如何防止错误的StopIteration被捕获?

时间:2012-06-02 23:55:33

标签: python iterator

有没有办法阻止StopIteration异常从不相关的代码中抛出(不必手动捕获它们)?

示例:loop_all想要循环遍历myiter迭代器,并在此完成时继续前进。除非some_dangerous_methodmyiter中的任何其他代码引发StopIteration,否则此方法有效。

def loop_all():
    myiter = myiter()
    try:
        while True:
            next(myiter) # <- I want exactly the StopIteration from this next method
    except StopIteration:
        pass

def myiter():
    some_dangerous_method() # what if this also raises a StopIteration?
    for i in some_other_iter():
        # here may be more code
        yield

有没有办法明确代码应该对StopIteration作出反应?

2 个答案:

答案 0 :(得分:3)

如果您正在调用的函数正在调用next(iter),并且没有处理StopIteration,那么该函数有一个错误。解决它。

答案 1 :(得分:1)

也许我错过了一些东西,但为什么不简单呢:

def myiter():
    try:
        some_dangerous_method()
    except StopIteration:
        pass # or raise a different exception
    for i in some_other_iter():
        # here may be more code
        yield