python使用decorator做异常处理,pythondecorator,如下代码使用ExpHan


如下代码使用ExpHandler修饰函数,在执行是自动添加try except代码,在出现异常时将异常信息交给handler去处理,可以指定不同的异常类型,根据类型来执行不同的异常处理逻辑。

import functoolsdef ExpHandler(*pargs):    """ An exception handling idiom using decorators"""    def wrapper(f):        if pargs:            (handler,li) = pargs            t = [(ex, handler)                 for ex in li ]            t.reverse()        else:            t = [(Exception,None)]        def newfunc(t,*args, **kwargs):            ex, handler = t[0]            try:                if len(t) == 1:                    f(*args, **kwargs)                else:                    newfunc(t[1:],*args,**kwargs)            except ex,e:                if handler:                    handler(e)                else:                    print e.__class__.__name__, ':', e        return functools.partial(newfunc,t)    return wrapperdef myhandler(e):    print 'Caught exception!', e# Examples# Specify exceptions in order, first one is handled first# last one last.@ExpHandler(myhandler,(ZeroDivisionError,))@ExpHandler(None,(AttributeError, ValueError))def f1():    1/0@ExpHandler()def f3(*pargs):    l = pargs    return l.index(10)if __name__=="__main__":    f1()    f3()

评论关闭