如何从 try catch 块内部中断 for 循环?
How to break for loop from inside of its try catch block?
我正在尝试找到一种方法来摆脱这个 for 循环如果 try except 块内的代码块(for 循环内)成功执行,并且没有调用异常。
这是对我不起作用的代码:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
因为在I15
执行成功后还在调用attempts列表中的J15
项
代码在这里:
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
如果代码已经在attempts
中尝试了整个attempt
,则用于抛出实际的异常
我相信最干净的方法是 continue
在 except
块内,然后 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
您需要 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
我正在尝试找到一种方法来摆脱这个 for 循环如果 try except 块内的代码块(for 循环内)成功执行,并且没有调用异常。
这是对我不起作用的代码:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
因为在I15
执行成功后还在调用attempts列表中的J15
项
代码在这里:
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
如果代码已经在attempts
attempt
,则用于抛出实际的异常
我相信最干净的方法是 continue
在 except
块内,然后 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
您需要 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