Here is a basic solution:
attempts = 5
for obj in iterable:
for _ in range(attempts):
try:
# code
break
except Exception as e:
# print(e)
pass
first of there needs to be a limit for the second loop (basically don't use a while True
(although possible but that would require adding unnecessary variables that can be avoided using a for loop
, basically I am saying that You shouldn't allow it to loop unconditionally)), otherwise it may run forever if the error persists
second, it is kind of important to print the error or except
a specific error, otherwise You may not know why it actually throws an exception. So either You except Exception
and then get to know what exception it was, for example there can be different exceptions so just so You know what went wrong, or have an expected exception (when You also don't need to print since You would know what was excepted (also instead of printing You could use some logging method))
obviously the attempts
value can be changed
also to note _
variable in this case basically tells python to ignore it/throw away because it isn't used anyways (although possible to put say i
and then print the attempt in the exception block (maybe that is helpful, again could use a logger instead of print))
also also reading one (or the only one) mentioned question in the comments under this question it said that a delay between attempts should also be added (could use time.sleep()
method) however that was more meant for if code is related to servers and sending requests and stuff (which may be the case but try that out yourself (if You were to add time.sleep()
I suggest adding it in the except
block tho try out yourself))