设计一个装饰器函数 retry,当被装饰的函数调用抛出指定的异常时,函数会被重新调用,直到达到指定的最大调用次数才重新抛出指定的异常。装饰器的使用示例如下:
@retry(times=10, traced_exceptions=ValueError, reraised_exception=CustomException)
def str2int(s):
pass
代码:
def retry(times,traced_exceptions=None,reraised_exception=None):
def decorate(fun):
def wrapper(*args,**kwargs):
n=times
while True:
print(n)
try:
return fun(*args,**kwargs)
except Exception as e:
if traced_exceptions and isinstance(e,traced_exceptions):
if n == 0:
if reraised_exception:
raise reraised_exception
n -= 1
return wrapper
return decorate
@retry(times=10, traced_exceptions=AttributeError, reraised_exception=Exception('123'))
def str2int(str):
return str.split('')
if __name__ == '__main__':
print(str2int(1))