Last active
December 16, 2015 23:49
-
-
Save sonkm3/5516180 to your computer and use it in GitHub Desktop.
python: raising exception from inside of generator function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
# simple generator function | |
def generator1(limit): | |
for count in range(limit): | |
yield count | |
# simple generator function with return | |
def generator2(limit, stop): | |
for count in range(limit): | |
if count > stop: | |
return | |
yield count | |
# simple generator function raising exception | |
def generator3(limit, stop): | |
for count in range(limit): | |
if count > stop: | |
raise | |
yield count | |
# simple generator function raising custom exception | |
def generator4(limit, stop): | |
class TempException(Exception): | |
pass | |
for count in range(limit): | |
if count > stop: | |
raise TempException | |
yield count | |
print 'generator1(5)' | |
gen1 = generator1(5) | |
while True: | |
try: | |
print gen1.next() | |
except Exception, ex: | |
print type(ex) | |
break | |
print 'StopIteration at the end of generator' | |
print '' | |
print 'generator2(5, 3)' | |
gen2 = generator2(5, 3) | |
while True: | |
try: | |
print gen2.next() | |
except Exception, ex: | |
print type(ex) | |
break | |
print 'StopIteration raised when generator returns' | |
print '' | |
print 'generator3(5, 3)' | |
gen3 = generator3(5, 3) | |
while True: | |
try: | |
print gen3.next() | |
except Exception, ex: | |
print type(ex) | |
break | |
print 'StopIteration raised when generator raises Exception' | |
print '' | |
print 'generator4(5, 3)' | |
gen4 = generator4(5, 3) | |
while True: | |
try: | |
print gen4.next() | |
except Exception, ex: | |
print type(ex) | |
try: | |
print gen4.next() | |
except Exception, ex: | |
print type(ex) | |
break | |
print 'First, TempException raised when generator raises TempException, and next gen4.next() call gets StopIteration' | |
print '' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output