print('revive from exception.') # do something to restore
def read_value(self):
print('here I will do something.') # do something.
在类中有一个方法read_value(),这个方法在多个地方被调用。由于某些原因,方法read_value有可能随机抛出Exception导致程序崩溃。所以需要对整个方法做try ... except处理。最丑陋的做法如下面的代码所示:
class Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.') # do something to restore
def read_value(self):
try: print('here I will do something.') # do something.
except Exception as e: print(f'exception {e} raised, parse exception.') # do other thing.
u = origin_func(*args, **kwargs) return u except Exception: return 'an Exception raised.'
return wrapperclass Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.') # do something to restore @catch_exception
def read_value(self):
print('here I will do something.') # do something.
这种写法,确实可以捕获到origin_func()的异常,但是如果在发生异常的时候,需要调用类里面的另一个方法来处理异常,这又应该怎么办?答案是给wrapper增加一个参数:self.
代码变为如下形式:
def catch_exception(origin_func):
def wrapper(self, *args, **kwargs):
try:
u = origin_func(self, *args, **kwargs) return u except Exception: self.revive() #不用顾虑,直接调用原来的类的方法
return 'an Exception raised.'
return wrapperclass Test(object):
def __init__(self):
pass
def revive(self):
print('revive from exception.') # do something to restore @catch_exception
def read_value(self):
print('here I will do something.') # do something.
只需要修改装饰器定义的部分,使用装饰器的地方完全不需要做修改。
下图为正常运行时的运行结果: