Why is else clause needed for try statement in python? [duplicate]

无人久伴 提交于 2019-12-05 01:57:16
Lennart Regebro

The difference is what happens if you get an error in the f.read() or f.close() code. In this case:

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

An error in f.read() or f.close() in this case would give you the log message "Unable to open foo", which is clearly wrong.

In this case, this is avoided:

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

And error in reading or closing would not cause a log write, but the error would rise uncatched upwards in the call stack.

else is used for code that must be executed if the try clause does not raise an exception.

The use else is better than an additional try clause because else avoids accidentally catching an exception that wasn't raised by the code protected by the try except statement.

From my understanding, the else clause is there to limit the scope of the try block to the code that you are trying to manage exceptions over. Alternatively your try blocks are larger and you may catch exceptions that you don't intend to catch.

@John:
I think in languages like Java, or other ones, you have different exceptions. For example something like FileNotFound Exception (or something like this, I am not sure of the name).
This way you can handle different exceptions and act accordingly. Then you know why the error has occurred, because of open or close.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!