我遇到了以下行为 . 使用了具有以下结构的代码块,

try:
    tup = tuple(<some_expression> for <_> in <iterator>)
except <SomeException>:
    pass

当在生成元组期间(在生成器表达式内)引发 SomeException 时, try - except 块没有处理它,而是整个程序停止 . 为什么会这样?有没有办法确保在genexpr中遇到异常 . 是"broadcasted"到外部范围?

具体例子

test.py

def input_generator():
    try:
        while True:
            for token in input().split():
                yield token
    except EOFError:
        pass


pyIn = input_generator()


def tuple_gen(n: int):
    try:
        while True:
            yield tuple(next(pyIn) for _ in range(n))
    except StopIteration:
        pass
    except ValueError:
        pass

if __name__ == "__main__":
    for a, b in tuple_gen(2):
        print(a, b)

考虑迭代 tuple_gen 生成器的实例,使用空文件作为输入(如 stdin ) . 遇到EOF时, pyIn 生成器终止,因此 next(pyIn) 引发 StopIteration ,但是程序停止,而不是被 except 块捕获 .

例如,保存一个空的 test.txt 文件(只是一个空行)并在(Windows)控制台上运行它

python test.py < test.txt

导致以下Traceback:

Traceback (most recent call last):
  File "test.py", line 16, in <genexpr>
    yield tuple(next(pyIn) for _ in range(n))
StopIteration

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "test.py", line 24, in <module>
    for a, b in tuple_gen(2):
  File "test.py", line 16, in tuple_gen
    yield tuple(next(pyIn) for _ in range(n))
RuntimeError: generator raised StopIteration