Thank you for opening my question. I tried to make my question clear but if there are still unclear parts because of my English, please let me know.
I am studying on Python coroutine and have read that calling a close() method on generator is similar to throwing GeneratorExit to the generator. So I tried like below.
def gen(n):
while True:
yield n
test = gen(10)
next(test)
test.throw(GeneratorExit)
Then GeneratorExit exception occurred. However when I tried test.close(), it did not raise any exception.
So I modified above code slightly;
def gen(n):
while True:
try:
yield n
except GeneratorExit:
break
test = gen(10)
next(test)
test.throw(GeneratorExit)
As GeneratorExit was handled, it was not raised but StopIteration exception occurred. I understand that if there is no more yield, StopIteration exception rises. However it was not raised when I tried test.close() again with the modified code.
Could you let me know what the difference between throwing GeneratorExit and calling close() method is?
To be more precise, I can understand why StopIteration and GeneratorExit exception occur with test.throw(GeneratorExit) but don't know why those exceptions are not raised when using test.close()
Thanks.