Reputation: 155
I have a loop that may raise an exception on one or more iterations. I want the loop to complete, THEN raise the first exception encountered, in the following example "raise on 4".
Example code:
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
Output:
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
I can use the logging module to record them which is fine but I would like to raise on the first Exception if possible.
I am still fairly new to Python so I'm not entirely sure if the way I have constructed the loop with the "else" statement is very Pythonic or correct.
Upvotes: 2
Views: 9326
Reputation: 250941
you can Append the errors to a list, and raise them later:
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
Upvotes: 1
Reputation: 1121714
You have to store e
in a separate variable:
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
Now firste
is only set when the exception is raised the first time.
You don't need to use else
in this case. Only use it when your for loop contains a break
statement, which would skip the else
suite, otherwise just put the test for firste
below the for
loop without using the redundant else
suite indentation.
Upvotes: 3