开发者

try...except...else v nested try...except

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 avo开发者_如何学编程ided 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..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.)


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()
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜