我有一个循环,它可能在一个或多个迭代中引发异常。我希望循环完成,然后引发遇到的第一个异常,在下面的示例“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式的还是正确的。在
您可以将错误附加到列表中,并在以后引发它们:
必须将
e
存储在单独的变量中:现在,
firste
只在第一次引发异常时设置。在在这种情况下,不需要使用
else
。仅当for循环包含break
语句时使用它,该语句将跳过else
套件,否则只需将firste
的测试放在for
循环下,而不使用冗余的else
套件缩进。在相关问题 更多 >
编程相关推荐