[英]How to break for loop from inside of its try catch block?
I'm trying to find a way to get out of this for loop if the code block inside the try except block (inside the for loop) is succesfully executed , and not calling the exception.如果 try except 块内的代码块(在 for 循环内)成功执行,而不是调用异常,我正在尝试找到一种方法来摆脱这个 for 循环。
Here's the code which doesn't work for me :这是对我不起作用的代码:
attempts = ['I15', 'J15']
for attempt in attempts:
try:
avar = afunc(attempt)
break
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
Because it's still calling the J15
item inside the attempts list after the I15
is succesfully executed因为在I15
成功执行后,它仍然在调用尝试列表中的J15
项
The code here :这里的代码:
except KeyError:
pass
if attempt == attempts[-1]:
raise KeyError
Is used to throw the actual exception if the code already tried the whole attempt
in attempts
用于抛出实际的异常,如果代码已经尝试了整个attempt
的attempts
You need the for … else
concept: https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops你需要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
I believe the cleanest way will be to continue
inside the except
block, and break
ing just after it.我相信最干净的方法是在except
块内continue
,并在它之后break
ing。 In this case you don't even have to use avar
(unless I misunderstood the question).在这种情况下,您甚至不必使用avar
(除非我误解了这个问题)。
attempts = ['I15', 'J15']
for attempt in attempts:
try:
afunc(attempt)
except KeyError:
continue
break
If you do need avar
for a later usage:如果您确实需要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.