【问题标题】:try...except...else v nested try...excepttry...except...else v 嵌套 try...except
【发布时间】:2011-07-09 05:26:08
【问题描述】:

Why is else clause needed for try statement in python ?

继续前进:

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 clause 解决的极端情况仍然可以通过nested try...except 避免,从而避免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)

【问题讨论】:

    标签: python


    【解决方案1】:

    try..except..else 可能不需要,但它可以很好。在这种情况下,我认为try..except..else 表单明显更好。

    仅仅因为您可以不使用语法元素,但这并不意味着它毫无用处。装饰器语法是纯粹的语法糖(我认为最明显的例子),for 循环只是美化了while 循环等等。 try..except..else 有一个好地方,我想说这是一个这样的地方。

    此外,这两个代码块远非等效。如果f.read() 引发异常(磁盘读取错误、文件内的数据损坏或其他类似问题),第一个将引发异常,但第二个将丢失它并认为一切正常。就我自己而言,我更喜欢这些方面的东西,更短,更容易理解:

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

    (这假设您想要捕获 file.readfile.close 中的错误。我真的不明白您为什么不这样做。)

    【讨论】:

    • 运行 python 2.5 并且无法使该代码工作。我得到无效的语法。
    • @eryksun:是的,忘记了。我刚刚检查了 Python 文档,The with statement 只是说“2.5 版中的新功能”。没有提到需要导入__future__,所以我想到了except as。 Python 文档中的“复合语句”页面没有提到它是什么时候添加的......我真的不记得了。
    【解决方案2】:

    实际上,并不总是需要你可以简单地这样做:

    f = None
    try:
      f = open('foo', 'r')
    except IOError:
      error_log.write('Unable to open foo\n')
    if f:
       data = f.read()
       f.close()
    

    【讨论】:

    • 但是你在None上调用read(),这会引发AttributeError
    • 你确定'if not f'会起作用吗?我想应该是'if f'
    • @Artsiom_Rudzenka 确实你是对的。固定的。我应该停止在 SO 中回答并去睡觉;)
    • 这仍然很不符合 Python 风格。
    • 真的。我不知道获胜答案中使用的方法很酷。
    猜你喜欢
    • 2016-08-30
    • 2014-08-23
    • 2020-11-26
    • 2013-11-21
    • 2019-06-26
    • 1970-01-01
    • 1970-01-01
    • 2013-08-11
    • 2017-05-14
    相关资源
    最近更新 更多