这是我们可能正在做的一项任务:在 for 循环中抓取一些网页。 然后其中一个页面发生了一些错误, 然后整个过程中断,我们还没有将结果存储到磁盘。 所以我们必须再次重新启动该过程。
我们为什么不多次重试其中一个步骤,我们可能会在第二次做对呢?
这是一个函数示例,在最终引发错误之前,使用 try 和 catch 块多次运行相同的任务。
import random
def multi_try_function_call( num_retries = 5 ):
for attempt_no in range(num_retries):
try:
print(f'************* try time at {attempt_no}*************')
failure_chance = random.random()
if failure_chance>0.6:
print('there is going to be error')
return 1/0
else:
print('no error')
return 0/1
except Exception as error:
if attempt_no < (num_retries - 1):
print(str(error))
else:
raise error
multi_try_function_call()
************* try time at 0*************
there is going to be error
division by zero
************* try time at 1*************
there is going to be error
division by zero
************* try time at 2*************
there is going to be error
division by zero
************* try time at 3*************
there is going to be error
division by zero
************* try time at 4*************
no error
0.0