How to call a function multi-times with try and catch before raise error in Python


Here is one task that we might be doing: scraping some webpages in a for loop. Then some error happens for one of the pages,
and then the whole process breaks, and we didn’t store results to disk yet. So we have to restart the process again.

Why don’t we just retry one of the steps multiple times, we may get it right at the second time?

Here is a function example to return the same task multiple times with try and catch block, before finally raise the error.

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

Author: robot learner
Reprint policy: All articles in this blog are used except for special statements CC BY 4.0 reprint policy. If reproduced, please indicate source robot learner !
  TOC