Skip to content

Instantly share code, notes, and snippets.

@Chris2048
Last active October 9, 2015 23:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Chris2048/3598432 to your computer and use it in GitHub Desktop.
Save Chris2048/3598432 to your computer and use it in GitHub Desktop.
handler function
#!/usr/bin/python2.7
# Simple example of using a 'handler' function
# -- Chris2048
def parseLine(line):
if line==True:
raise Exception()
return "foo"
def parseLines(lines, handler):
for line in lines:
try:
yield parseLine(line)
except Exception, e:
try:
yield handler(e, line)
except SkipException:
continue
one = [False, True, False]
def replacehandler(e, line):
print "Exception '%s' was thrown!" % e.__repr__()
if line==True:
return "bar"
print "\nwith replace:"
oner = parseLines(one, replacehandler)
print [i for i in oner]
class SkipException(Exception):
pass
def skiphandler(e, line):
print "Exception '%s' was thrown!" % e.__repr__()
raise SkipException()
print "\nwith skip:"
oner = parseLines(one, skiphandler)
print [i for i in oner]
def stophandler(e, line):
print "Exception '%s' was thrown!" % e.__repr__()
raise StopIteration()
print "\nwith stop"
oner = parseLines(one, stophandler)
print [i for i in oner]
class SomeException(Exception):
pass
def excepthandler(e, line):
print "Exception '%s' was thrown!" % e.__repr__()
raise SomeException()
print "\nwith except:"
try:
oner = parseLines(one, excepthandler)
print [i for i in oner]
except Exception as e:
print "Got exception '%s'!" % e.__repr__()
def askhandler(e, line):
action = raw_input("Got exception '%s',\nWhat do I do? (Skip, Return, sTop, rAise):\n" % e.__repr__())
while action not in ('s','S','r','R','t','T','a','A'):
print "Please enter valid value!"
action = raw_input("Got exception '%s',\nWhat do I do? (Skip, Return, sTop, rAise):\n" % e.__repr__())
if action in ('s','S'):
return skiphandler(e, line)
if action in ('t','T'):
return stophandler(e, line)
if action in ('a','A'):
return excepthandler(e, line)
if action in ('r','R'):
return raw_input("Replace with what?:\n")
print "\nwith ask:"
oner = parseLines(one, askhandler)
print [i for i in oner]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment