crunkchitis crunkchitis - 6 months ago 23
Python Question

Repetitive Try and Except Clauses

I've created a bunch of functions and I need very similar except clauses in all of them, but I hate having so many lines of try and except clauses and the same code inside of each function. For example:

import sys
import random

def foo():
num=random.random()
try:
if num>0.5: print 'OK'
elif num>0.25: raise NameError('Too Small')
else: raise KeyboardInterrupt
except NameError:
print "%s had a NameError" % sys._getframe().f_code.co_name
except:
print "%s had a different Error" % sys._getframe().f_code.co_name

def bar():
num=random.random()
try:
if num>0.8: print 'OK'
elif num>0.6: raise NameError('Too Small')
else: raise KeyboardInterrupt
except NameError:
print "%s had a NameError" % sys._getframe().f_code.co_name
except:
print "%s had a different Error" % sys._getframe().f_code.co_name


The code after "try" is different for the functions, but the code after "except" is the same. I want to consolidate those except statements so they don't make my code look so cramped. Is there a good way to do this?

Answer Source

Python Decorators are what you want.

You said the except block is always the same. Make a custom decorator that does what you want. You'll have to apply this to each function/method but it sure does save duplication.

def handleError(function):
    def handleProblems():
        try:
            function()
        except Exception:
            print "Oh noes"
    return handleProblems


@handleError
def example():
   raise Exception("Boom!")

When calling a method with the decorator applied:

>>> 
>>> example()
Oh noes
>>> 

You will need to change the exception types as well as what you do, but you get the jist of where I'm going with this.