3

Why is else clause needed for try statement in python ?

Taking it forward:

try:
  f = open('foo', 'r')
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)
else:
  data = f.read()
  f.close()

It occurs to me that the corner case solved by else clause still can be avoided by a nested try...except avoiding the need of else? :

try:
  f = open('foo', 'r')
  try:
    data = f.read()
    f.close()
  except:
    pass 
except IOError as e:
  error_log.write('Unable to open foo : %s\n' % e)
Community
  • 1
  • 1
Vaibhav Bajpai
  • 16,374
  • 13
  • 54
  • 85

2 Answers2

6

try..except..else may not be needed, but it can be nice. In this case, the try..except..else form is distinctly nicer, in my opinion.

Just because you can do without an element of syntax, doesn't make it useless. Decorator syntax is purely syntax sugar (the most obvious example, I think), for loops are just glorified while loops, et cetera. There's a good place for try..except..else and I would say this is one such place.

Besides, those two blocks of code are far from equivalent. If f.read() raises an exception (disk read error, data corruption inside the file or some other such problem), the first will raise an exception as it should but the second will lose it and think that everything has worked. For myself, I would prefer something more along these lines, which is shorter and still easier to understand:

try:
    with open('foo', 'r') as f:
        data = f.read()
except IOError as e:
    error_log.write('Unable to open foo : %s\n' % e)

(This assumes that you want to catch errors in file.read and file.close. And I can't really see why you wouldn't.)

Chris Morgan
  • 86,207
  • 24
  • 208
  • 215
  • running python 2.5 and can't make that code work. I get invalid syntax. – Manuel Salvadores Jul 09 '11 at 05:56
  • @eryksun: ah yes, forgot about that. I just checked the Python docs and [The `with` statement](http://docs.python.org/reference/compound_stmts.html#with) just says "New in version 2.5." without mentioning the `__future__` import needed, so I thought of the `except as`. The "Compound Statements" page in the Python docs doesn't mention when it was added... and I can't really remember. – Chris Morgan Jul 09 '11 at 06:03
0

Actually, is not always needed you can simply do:

f = None
try:
  f = open('foo', 'r')
except IOError:
  error_log.write('Unable to open foo\n')
if f:
   data = f.read()
   f.close()
Manuel Salvadores
  • 16,287
  • 5
  • 37
  • 56