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

独自空忆成欢 提交于 2019-12-06 20:09:30

问题


In Python the try statement supports an else clause, which executes if the code in try block does not raise an exception. For example:

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

Why is the else clause needed? Can't we write the above code as follows :

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

Won't the execution proceed to data = f.read() if open does not raise an exception?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/4836139/why-is-else-clause-needed-for-try-statement-in-python

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