簡體   English   中英

如何從它的 try catch 塊內部中斷 for 循環?

[英]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

用於拋出實際的異常,如果代碼已經嘗試了整個attemptattempts

你需要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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM