else in try/except
Chris Kaynor
ckaynor at zindagigames.com
Mon Nov 14 18:12:13 EST 2011
On Mon, Nov 14, 2011 at 2:59 PM, MRAB <python at mrabarnett.plus.com> wrote:
> On 14/11/2011 21:53, Ethan Furman wrote:
>>
>> The code in 'else' in a 'try/except/else[/finally]' block seems
>> pointless to me, as I am not seeing any difference between having the
>> code in the 'else' suite vs having the code in the 'try' suite.
>>
>> Can anybody shed some light on this for me?
>>
> The difference is that if an exception occurs in the else block it
> won't be caught by the exception handlers of the try statement.
Consider the examples:
try:
a
raise RuntimeError()
except RuntimeError:
pass
vs
try:
a
except RuntimeError:
pass
else:
raise RuntimeError()
The first example will not raise an exception, while the second will
result in a RuntimeError.
Effectively, the first block will either:
1) If the "a" block raises a RuntimeError, continue,
2) If the "a" block raised any other error, propergate it,
3) If the "a" block does not raise an exception, continue.
while the second block will either:
1) If the "a" block raises a RuntimeError, continue,
2) If the "a" block raised any other error, propergate it,
3) If the "a" block does not raise an exception, raise a RuntimeError.
Note the difference in the 3rd case.
> --
> http://mail.python.org/mailman/listinfo/python-list
>
More information about the Python-list
mailing list