else in try/except

Arnaud Delobelle arnodel at gmail.com
Mon Nov 14 18:03:55 EST 2011


On 14 November 2011 21:53, Ethan Furman <ethan at stoneleaf.us> 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?

Exceptions in the else clause will not be caught. Look at the
difference between the two try clauses below:

>>> def f(): raise TypeError
...
>>> try:
...    print("try")
...    f()
... except TypeError:
...    print("except")
...
try
except
>>> try:
...    print("try")
... except TypeError:
...    print("except")
... else:
...    f()
...
try
Traceback (most recent call last):
  File "<stdin>", line 6, in <module>
  File "<stdin>", line 1, in f
TypeError
>>>

HTH

-- 
Arnaud



More information about the Python-list mailing list