3 回答
TA贡献1836条经验 获得超4个赞
做一个while True内部的for循环,把你的try代码中,并突破从while只有当你的代码的成功循环。
for i in range(0,100):
while True:
try:
# do stuff
except SomeSpecificException:
continue
break
TA贡献1789条经验 获得超10个赞
我更喜欢限制重试的次数,这样,如果该特定项目有问题,您最终将继续进行下一个,因此:
for i in range(100):
for attempt in range(10):
try:
# do thing
except:
# perhaps reconnect, etc.
else:
break
else:
# we failed all the attempts - deal with the consequences.
TA贡献1744条经验 获得超4个赞
这是一种与其他解决方案类似的解决方案,但是如果未按规定的次数或重试次数失败,则会引发异常。
tries = 3
for i in range(tries):
try:
do_the_thing()
except KeyError as e:
if i < tries - 1: # i is zero indexed
continue
else:
raise
break
添加回答
举报