[英]How to break for loop from inside of its try catch block?
如果 try except 块内的代码块(在 for 循环内)成功执行,而不是调用异常,我正在尝试找到一种方法来摆脱这个 for 循环。
这是对我不起作用的代码:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
因为在I15
成功执行后,它仍然在调用尝试列表中的J15
项
这里的代码:
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
用于抛出实际的异常,如果代码已经尝试了整个attempt
的attempts
你需要for … else
概念: https : //docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
except KeyError:
# error, let's try another item from attempts
continue
else:
# success, let's get out of the loop
break
else:
# this happens at the end of the loop if there is no break
raise KeyError
我相信最干净的方法是在except
块内continue
,并在它之后break
ing。 在这种情况下,您甚至不必使用avar
(除非我误解了这个问题)。
attempts = ['I15', 'J15']
for attempt in attempts:
try:
afunc(attempt)
except KeyError:
continue
break
如果您确实需要avar
以供以后使用:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
except KeyError:
continue
break
print(avar) # avar is a available here, as long as at least one attempt was successful
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.