【问题标题】:How to break for loop from inside of its try catch block?如何从其 try catch 块内部中断 for 循环?
【发布时间】:2020-04-08 21:57:07
【问题描述】:

我正在尝试找到一种方法来摆脱这个 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成功执行后,它仍在尝试列表中调用J15

这里的代码:

    except KeyError:
        pass
        if attempt == attempts[-1]:
            raise KeyError

如果代码已经在attempts中尝试了整个attempt,则用于抛出实际异常

【问题讨论】:

    标签: python python-3.x python-2.7 for-loop try-except


    【解决方案1】:

    您需要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
    

    【讨论】:

      【解决方案2】:

      我相信最干净的方法是在 except 块内的 continue 和紧随其后的 breaking。在这种情况下,您甚至不必使用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
      

      【讨论】:

      • 嗯,是的,我仍然需要 avar,因为 try except 块需要为变量生成一个值
      • @DyaksaHanindito 如果两次尝试都不成功,那么最后没有定义avar
      猜你喜欢
      • 2015-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多