使用Python'with'语句时捕获异常 - 第2部分

时间:2011-03-05 18:21:20

标签: python exception exception-handling with-statement

这是问题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而没有捕获它会发生什么?它显然被外部的“除外”声明所吸引,但那可能不是我真正想要的 你可以说好,只需用另一个try-except包装some_code,依此类推,但我知道异常可以来自任何地方,并且不可能保护每一段代码。
总而言之,我只是想打印'错误',当且仅当open('foo.txt','a')引发异常时,所以我在这里问为什么以下代码不是标准的建议方式这样做:

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

with f:
    #
    # some_code
    #

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

谢谢!

1 个答案:

答案 0 :(得分:14)

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