繁体   English   中英

在for循环期间引发异常,并在python中的下一个索引处继续

[英]Raising an exception during for loop and continuing at next index in python

我整天都在挣扎,我似乎无法解决这个问题。 我应该写一个Exception类,然后在迭代过程中引发它,然后从我停下来的地方继续。

    class OhNoNotTrueException(Exception):
    """Exception raised when False is encountered
    Attributes:
    message -- explanation of the error"""

    def __init__(self, value):
    self.value = value



   am_i_true_or_false = [True, None, False, "True", 0, "", 8, "False", "True", "0.0"]

  try:
     for i in am_i_true_or_false:
        if i is False:
           raise OhNoNotTrueException(i)
           continue                      #<--this continue does not work
     else:
        print(i, "is True")

  except OhNoNotTrueException as e:
  print(e.value, "is False")

但是,即使将continue放入之后,也无法将迭代返回到上一个索引。 我不确定这是否是唯一的方法,但是我在这里摔断了头。 有人想要破解吗?

我应该得到以下输出:

真是真的。

没有错

假是假

真是真的。

0为假

是假的

8是真的。

假是真的。

真是真的。

0.0是正确的。

引发异常后的所有内容将永远无法到达,您将被带到循环之外,就像try块中的所有内容从未发生过一样。 因此,您需要在循环内尝试/例外:

In [5]: for i in am_i_true_or_false:
   ...:     try:
   ...:         if i is False:
   ...:             raise OhNoNotTrueException(i)
   ...:         else:
   ...:             print(i, "is not False")
   ...:     except OhNoNotTrueException as e:
   ...:         print(e.value, "is False")
   ...:         
True is not False
None is not False
False is False
True is not False
0 is not False
 is not False
8 is not False
False is not False
True is not False
0.0 is not False

注意,如果您的try块包含循环,会发生什么:

In [2]: try:
   ...:     for i in am_i_true_or_false:
   ...:         if i is False:
   ...:             raise Exception()
   ...:         else:
   ...:             print(i,"is not False")
   ...: except Exception as e:
   ...:     continue
   ...: 
  File "<ipython-input-2-97971e491461>", line 8
    continue
    ^
SyntaxError: 'continue' not properly in loop

您应该在try / except块之外进行循环。 然后,将通过try catch检查一个单独的列表条目,然后循环将继续执行下一个:

for i in am_i_true_or_false:
    try:
       if i is False:
           raise OhNoNotTrueException(i)
       else:
           print("{} is True".format(i))
    except OhNoNotTrueException as e:
        print("{} is False".format(e.value))

在执行此操作时,循环将执行到第一个异常,然后执行except块,然后程序结束。 在这种情况下,无法达到continue ,因为您引发了一个异常,该异常将在except块中捕获。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM