python使用decorator做异常处理,pythondecorator,如下代码使用ExpHan
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()
相关内容
- python gzip压缩文件,pythongzip,下面的代码实现用gzip
- python导出linux用户权限,pythonlinux,要换linux服务器,由
- python目录遍历代码,python目录,如下python实现目录
- Python 正则表达式(re模块)操作指南,pythonre,原文出处:
- python使用126发邮件代码,python126发邮件,写了个用smtpl
- python读写文件方法介绍,python读写介绍,open 打开文件使
- 动态修改python系统路径,动态python路径,默认情况下py
- Python RGB 和HSV颜色相互转换,pythonhsv,Python RGB 和
- python对MySqldb模块的简单封装代码,pythonmysqldb封装,#!/
- python使用pymongo连接MongoDB,pymongomongodb,本文是一个Pyth
评论关闭