【问题标题】:Catching an exception while using a Python 'with' statement - Part 2在使用 Python 'with' 语句时捕获异常 - 第 2 部分
【发布时间】:2011-07-09 12:20:44
【问题描述】:

这是问题Catching an exception while using a Python 'with' statement的延续。
我是个新手,我在 GNU/linux 上使用 Python 3.2 测试了以下代码。

在上述问题中,提出了与此类似的方法来从“with”语句中捕获异常:

try:
    with open('foo.txt', 'a'):
        #
        # some_code
        #
except IOError:
    print('error')

这让我想知道:如果 some_code 引发 IOError 而不捕获它会发生什么?它显然被外部的“except”语句所捕获,但这不是我真正想要的。
你可以说好吧,只是用另一个 try-except 包装 some_code,等等,但我知道异常可能来自任何地方,不可能保护每一段代码。
总而言之,当且仅当 open('foo.txt', 'a') 引发异常时,我只想打印'error',所以我在这里问为什么以下代码不是标准的建议方式这样做:

try:
    f = open('foo.txt', 'a')
except IOError:
    print('error')

with f:
    #
    # some_code
    #

#EDIT: 'else' statement is missing, see Pythoni's answer

谢谢!

【问题讨论】:

  • 有关在复合 with 语句中可以引发异常的各个位置之间的详细区别,请参阅 this answer on the original question
  • 对我来说,我不在乎异常是在 withable 的初始化时发生还是在我使用 withable 时发生,因为它是一个自定义异常,在任何一种情况下最终都会以相同的方式处理。所以实际上第一个例子最适合我。

标签: python exception exception-handling with-statement


【解决方案1】:
try:
    f = open('foo.txt', 'a')
except IOError:
    print('error')
else:
    with f:
        #
        # some_code
        #

【讨论】:

  • 你说的很对,我忘了把'with'放在'else'下面。
  • 无论如何,我的主要问题是我的猜测是否正确:对另一个较老问题的答案真的比这种方法更糟糕吗?
  • 好的,我想这是在这种情况下处理异常的最佳方法,所以这是我接受的答案。也许您也可以在另一个问题stackoverflow.com/questions/713794/… 中复制这个
猜你喜欢
  • 2010-10-17
  • 2011-12-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-03
  • 2014-01-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多