我不确定以下代码中到底发生了什么:
def coroutine():
lst = []
try:
while True:
item = (yield lst)
if item == 3:
raise ValueError
print('append {}'.format(item))
lst.append(item)
except GeneratorExit:
print('GeneratorExit')
crt = coroutine()
next(crt)
print(crt.send(1))
print(crt.send(2))
try:
print(crt.send(3))
except ValueError:
pass
print(crt.send(4))
这输出:
append 1
[1]
append 2
[1, 2]
Traceback (most recent call last):
File "D:\Documents and Settings\Brecht\Desktop\crt.py", line 25, in <module>
print(crt.send(4))
StopIteration
当使用调试器单步执行代码时, on raise ValueError
,执行跳转到except GeneratorExit:
,但不执行此 except 子句的主体(不打印“GeneratorExit”)。为什么不?
除此之外,我不认为我可以在协程引发异常后以任何方式恢复协程?有什么特别的理由不允许这样做吗?这至少在我的特定用例中很有用:)