在使用Python'with'语句时捕获异常 - 第2部分 [英] Catching an exception while using a Python 'with' statement - Part 2

查看:153
本文介绍了在使用Python'with'语句时捕获异常 - 第2部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是在使用时捕获异常的问题的延续一个Python'与'语句

我很新手,我在GNU / linux上用Python 3.2测试了以下代码。

this is a continuation of question Catching an exception while using a Python 'with' statement.
I'm quite e newbie and I tested the following code with Python 3.2 on GNU/linux.

在上述问题中,提出了一个类似于此的问题,以从with语句中捕获异常:

In the above-mentioned question, something similar to this was proposed to catch an exception from a 'with' statement:

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

这让我想知道:如果some_code引发IOError而不捕捉它会怎么样?它显然被外部的'except'语句所捕获,但这不可能是我真正想要的。

你可以说ok,只是用另外一个try-except来代替some_code,等等,但是我知道例外可以来自各地,不可能保护每一段代码。

总而言之,只要打开('foo.txt','a')即可打印'error'引起例外,所以我在这里问为什么以下代码不是标准建议的方法:

That makes me wonder: what happens if some_code raises an IOError without catching it? It's obviously caught by the outer 'except' statement, but that could not be what I really wanted.
You could say ok, just wrap some_code with another try-except, and so on, but I know that exceptions can come from everywhere and it's impossible to protect every piece of code.
To sum up, I just want to print 'error' if and only if open('foo.txt', 'a') raises the exception, so I'm here to ask why the following code is not the standard suggested way of doing this:

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

with f:
    #
    # some_code
    #

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

谢谢!

推荐答案

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

这篇关于在使用Python'with'语句时捕获异常 - 第2部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆