0

有没有办法防止StopIteration不相关的代码抛出异常(无需手动捕获它们)?

示例:loop_all想要遍历myiter迭代器并在这个迭代器完成后继续前进。除非some_dangerous_method或任何其他代码myiter引发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代码应该对哪个做出反应?

4

2 回答 2

3

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

于 2012-06-03T00:02:46.633 回答
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
于 2012-06-03T16:41:21.660 回答