Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncatchable Exceptions in Generators

I'm having issues with Python 2.7, whereby an exception raised from a generator is not catchable.

I've lost a fair amount of time, twice, with this behavior.

def gen_function():
    raise Exception("Here.")

    for i in xrange(10):
        yield i

try:
    gen_function()
except Exception as e:
    print("Ex: %s" % (e,))
else:
    print("No exception.")

Output:

No exception.
like image 966
Dustin Oprea Avatar asked Nov 27 '25 18:11

Dustin Oprea


2 Answers

gen_function() will give you generator object

You need to call next() function to invoke the code.

You can do it directly with next function

g = gen_function()
next(g)

or

for i in g:
    pass # or whatever you want

Both will trigger an exception

like image 183
Jan Vorcak Avatar answered Nov 30 '25 10:11

Jan Vorcak


Calling a generator just gives you the generator object. No code in the generator is actually executed, yet. Usually this isn't obvious since you often apply the generator immediately:

for x in gen_function():
    print x

In this case the exception is raised. But where? To make it more explicit when this happens I've made explicit the for ... in loop (this is essentially what it does behind-the-scenes):

generator_obj = gen_function()  # no exception
it = iter(generator_obj)  # no exception (note iter(generator_obj) is generator_obj)
while True:
    try:
        x = it.next()  # exception raised here
    except StopIteration:
        break

    print x
like image 27
Claudiu Avatar answered Nov 30 '25 09:11

Claudiu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!