Mil*_*ano 14 python iteration loops exception-handling exception
是否有一个命令,例如break和continue可能重复最近的迭代?
例如,抛出异常时.
for i in range(0,500):
try:
conn = getConnection(url+str(i))
doSomething(conn)
except:
repeat
Run Code Online (Sandbox Code Playgroud)
让我们有一个i变量值的迭代6.在此迭代期间,发生了一些连接错误.我想重复这个迭代.
有没有可以做到的命令?
我当然可以这样做:
i=0
while i!=500:
try:
conn = getConnection(url+str(i))
doSomething(conn)
i+=1
except:
pass
Run Code Online (Sandbox Code Playgroud)
iCo*_*dez 13
不,没有命令在Python中"回绕"for循环.
你可以while True:在for循环中使用一个循环:
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
except Exception: # Replace Exception with something more specific.
continue
else:
break
Run Code Online (Sandbox Code Playgroud)
或没有else::
for i in range(500):
while True:
try:
conn = getConnection(url+str(i))
doSomething(conn)
break
except Exception: # Replace Exception with something more specific.
continue
Run Code Online (Sandbox Code Playgroud)
但我个人认为您提出的解决方案更好,因为它避免了缩进级别.