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.)