I am not clear about the behavior of catching GeneratorExit in a while loop, here is my code:
# python
Python 2.6.6 (r266:84292, Sep 4 2013, 07:46:00)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def func():
... while True:
... try:
... yield 9
... except GeneratorExit:
... print "Need to do some clean up."
...
>>> g = func()
>>> g.next()
9
>>> g.close()
Need to do some clean up.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
RuntimeError: generator ignored GeneratorExit
It appears when g.close() is called, GeneratorExit is catched because "Need to do some clean up." is printed, but I do not understand why there is a RuntimeError.
"It appears when g.close() is called, GeneratorExit is catched"
Yes, GeneratorExit is raised when the generator's close() method is called.
See the following documentation:
https://docs.python.org/2/library/exceptions.html
And the exception will cause a RuntimeError
After the aforementioned exception is raised inside the loop, it is actually handled, and you see the printed error message. But, the loop continues, and it still tries to yield 9. That's when you see the RuntimeError. Therefore, moving the exception handling outside of your loop solves the problem.
Just add a return
statement after printing "Need to do some clean up."
. Everything works fine then :). This the preferred way, esp when you cannot move your exception out
while True:
try:
yield 9
except GeneratorExit:
print "Need to do some clean up."
return
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With