joe*_*ker 7 python generator python-2.7
我在Python 2.7.5中发现了一个奇怪的行为except:
:
def generator():
try:
raise Exception()
except:
yield
raise
list(generator())
Run Code Online (Sandbox Code Playgroud)
此代码失败 TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType
为什么Python会这样做而不是重新引发异常,就像yield
之前没有那样raise
?
(显然Python 3修复了这个疣,函数会产生一个[None]列表,如你所料.)
(解决方法是异常存储在一个变量:except Exception as e: yield; raise e
)