懒惰促进发明。话说我每次写代码总是每逢函数必套try except ,真的是心累,所以为啥不弄个装饰器放上去。
这个装饰器还得满足几点要求:
def try_except2(func): def handler(*args, **kwargs): try: func(*args, **kwargs) except (BaseException,Exception) as e: print(traceback.format_exc()) #用于记录错误日志的 return "这里的return替代了error2所返回的 a" return handler@try_except2 def error2(x): a=x/0 return a a=error2(1) print(a)>>>ZeroDivisionError: division by zero
>>>这里的return替代了error2所返回的 a
简单的来说就是,如果函数运行正常,返回a,x,0;如果函数运行错误,依旧能够返回三个参数"the","is","error" 。而且这三个参数,是可以指定的。当然也可以多加一个参数,传递指定的日志信息。
def try_except(*parames): def wrap(func): def handler(*args, **kwargs): try: func(*args, **kwargs) except (BaseException,Exception) as e: print(traceback.format_exc()) return parames #此处返回的是装饰参数里的 "the","is","error" 三个返回值 return handler return wrap@try_except("the","is","error") def error1(x): a=x/0 return a ,x ,0 a,b,c=error1(3) print(a,b,c)>>>ZeroDivisionError: division by zero
>>>the is error
完美,再也不怕程序意外错误了