2

我有一个循环,可能会在一次或多次迭代中引发异常。我希望循环完成,然后引发遇到的第一个异常,在以下示例中为“raise on 4”。

示例代码:

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

输出:

0
1
2
3
4
raise on 4
5
6
raise on 6
7
8
9
Traceback (most recent call last):
  File "<stdin>", line 7, in <module>
Exception: raise on 6

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

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

4

2 回答 2

3

您必须存储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

Nowfirste仅在第一次引发异常时设置。

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

于 2012-12-05T11:29:06.100 回答
1

您可以将错误附加到列表中,稍后再提出:

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
于 2012-12-05T11:34:49.827 回答