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)
try..except..elsemay not be needed, but it can be nice. In this case, thetry..except..elseform 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),
forloops are just glorifiedwhileloops, et cetera. There’s a good place fortry..except..elseand 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:(This assumes that you want to catch errors in
file.readandfile.close. And I can’t really see why you wouldn’t.)