为什么python中的try语句需要else子句?

时间:2011-01-29 09:39:41

标签: python exception-handling

在Python中,try语句支持else子句,如果try块中的代码不引发异常,则执行该子句。例如:

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

为什么需要else子句?我们不能按如下方式编写上述代码:

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

如果open没有引发异常,执行是否会继续执行data = f.read()

4 个答案:

答案 0 :(得分:14)

如果在f.read()或f.close()代码中出现错误,则会出现差异。在这种情况下:

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

在这种情况下,f.read()f.close()中的错误会为您提供日志消息"Unable to open foo",这显然是错误的。

在这种情况下,可以避免这种情况:

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

读取或关闭时的错误不会导致日志写入,但错误会在调用堆栈中向上移动。

答案 1 :(得分:3)

如果else子句没有引发异常,则

try用于必须执行的代码。

使用else优于额外的try子句,因为else可以避免意外捕获由try except语句保护的代码未引发的异常。

答案 2 :(得分:2)

根据我的理解,else子句用于将try块的范围限制为您尝试管理异常的代码。或者,您的try块更大,您可能会捕获您不想捕获的异常。

答案 3 :(得分:0)

@约翰:
我认为在Java或其他语言中,您有不同的例外。例如像FileNotFound Exception(或类似的东西,我不确定名称) 这样您就可以处理不同的异常并采取相应的行动。然后你知道为什么错误发生了,因为打开或关闭。

相关问题