Skip to content

Instantly share code, notes, and snippets.

@sonkm3
Last active December 16, 2015 23:49
Show Gist options
  • Save sonkm3/5516180 to your computer and use it in GitHub Desktop.
Save sonkm3/5516180 to your computer and use it in GitHub Desktop.
python: raising exception from inside of generator function.
# -*- 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 ''
@sonkm3
Copy link
Author

sonkm3 commented May 4, 2013

output

generator1(5)
0
1
2
3
4
<type 'exceptions.StopIteration'>
StopIteration at the end of generator

generator2(5, 3)
0
1
2
3
<type 'exceptions.StopIteration'>
StopIteration raised when generator returns

generator3(5, 3)
0
1
2
3
<type 'exceptions.StopIteration'>
StopIteration raised when generator raises Exception

generator4(5, 3)
0
1
2
3
<class '__main__.TempException'>
<type 'exceptions.StopIteration'>
First, TempException raised when generator raises TempException, and next gen4.next() call gets StopIteration

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment