本文更新地址:http://blog.csdn.net/tanzuozhev
采用try-exception是python捕获异常的常用方式,但在代码频繁的使用着实麻烦,所以采用装饰器对try-catch进行了封装。
def get_decorator(errors=(Exception, ), default_value=''):
def decorator(func):
def new_func(*args, **kwargs):
try:
return func(*args, **kwargs)
except errors, e:
print "Got error! ", repr(e)
return default_value
return new_func
return decorator
try_except = get_decorator(default_value='default')
a = {}
@try_except
def example1(a):
return a['b']
@try_except
def example2(a):
return doesnt_exist()
print example1(a)
print example2(a)
#Got error! KeyError('b',)
#default
#Got error! NameError("global name 'doesnt_exist' is not #defined",)
#default
import sys,traceback
def try_except(f):
def handle_problems(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception:
exc_type, exc_instance, exc_traceback = sys.exc_info()
formatted_traceback = ''.join(traceback.format_tb(exc_traceback))
message = '\n{0}\n{1}:\n{2}'.format(
formatted_traceback,
exc_type.__name__,
exc_instance
)
# raise exc_type(message)
print(exc_type(message))
# 其他你喜欢的操作
finally:
pass
return handle_problems
@try_except
def chu(x, y):
return(x/y)
chu(1,0)
# File "", line 5, in handle_problems
# return f(*args, **kwargs)
# File "", line 22, in chu
# return(x/y)
# ZeroDivisionError:
# division by zero
参考:http://stackoverflow.com/questions/9386592/repetitive-try-and-except-clauses
http://stackoverflow.com/questions/9005941/python-exception-decorator-how-to-preserve-stacktrace
http://stackoverflow.com/questions/23218974/wrapping-class-method-in-try-except-using-decorator