循环完成后在for循环中遇到引发第一个异常

2024-09-27 23:27:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个循环,它可能在一个或多个迭代中引发异常。我希望循环完成,然后引发遇到的第一个异常,在下面的示例“raiseon4”。在

示例代码:

e = None
for x in range(10):
    try:
        print x
        if x == 4:
            raise Exception('raise on 4')
        if x == 6:
            raise Exception('raise on 6')
    except Exception as e:
        print e
        continue
else:
    if e:
        raise

输出:

^{pr2}$

我可以使用日志记录模块来记录它们,这很好,但是如果可能的话,我想在第一个异常上提出。在

我对Python还是相当陌生的,所以我不能完全确定我用“else”语句构建循环的方式是非常Python式的还是正确的。在


Tags: 代码innone示例forifon记录
2条回答

您可以将错误附加到列表中,并在以后引发它们:

In [25]: errors=[]

In [26]: for x in range(10):
        try:
                print x
                if x == 4:
                        raise Exception('raise on 4')
                if x == 6:
                        raise Exception('raise on 6')
        except Exception as e:
                    errors.append(e)
                    continue
   ....:             
0
1
2
3
4
5
6
7
8
9

In [27]: for error in errors:
    raise error
   ....: 
                                     -
Exception                                 Traceback (most recent call last)
<ipython-input-27-1f1d8ab5ba84> in <module>()
      1 for error in errors:
  > 2     raise error

Exception: raise on 4

必须将e存储在单独的变量中:

firste = None
for x in range(10):
    try:
        print x
        if x == 4:
            raise Exception('raise on 4')
        if x == 6:
            raise Exception('raise on 6')
    except Exception as e:
        if firste is None:
            firste = e
        continue

if firste is not None:
    raise firste

现在,firste只在第一次引发异常时设置。在

在这种情况下,不需要使用else。仅当for循环包含break语句时使用它,该语句将跳过else套件,否则只需将firste的测试放在for循环下,而不使用冗余的else套件缩进。在

相关问题 更多 >

    热门问题