python - What happens when a coroutine raises an exception? -


i'm not sure happens in following piece of code:

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)) 

this outputs:

append 1 [1] append 2 [1, 2]  traceback (most recent call last):   file "d:\documents , settings\brecht\desktop\crt.py", line 25, in <module>     print(crt.send(4)) stopiteration 

when stepping through code debugger, on raise valueerror, execution jumps except generatorexit:, body of except clause not executed ('generatorexit' not printed). why not?

aside that, don't suppose can in way resume coroutine after has thrown exception? there particular reason not allow this? useful @ least in particular use case :)

when throw exception, code flow always interrupted. cannot resume interrupted generator once throw exception in it.

from pep 342 (coroutines via enhanced generators):

as next() method, send() method returns next value yielded generator-iterator, or raises stopiteration if generator exits normally, or has exited. if generator raises uncaught exception, propagated send()'s caller.

as debugger jumping except line: threw exception , interpreter testing if exception caught line or not. because it'll catch generatorexit, generator exits @ point.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -