python try:except:finally

2024-04-24 06:49:06 发布

您现在位置:Python中文网/ 问答频道 /正文

# Open new file to write
file = None
try:
    file = open(filePath, 'w')
except IOError:
    msg = ("Unable to create file on disk.")
    file.close()
    return
finally:
    file.write("Hello World!")
    file.close()

上面的代码是从函数中提取的。用户的系统之一正在报告第行中的错误:

file.write("Hello World!")

错误:

AttributeError: 'NoneType' object has no attribute 'write'

问题是,如果python无法打开给定的文件,就会执行'except'块,它必须 返回,但控件将被转移到引发给定错误的行。“file”变量的值为“None”。

有什么线索吗?


Tags: tononehellonewworldclose错误open
3条回答

如果文件未打开,则行file = open(filePath, 'w')将失败,因此不会为file分配任何内容。

然后,运行except子句,但文件中没有任何内容,因此file.close()失败。

finally子句始终运行,即使出现异常。由于file仍然是None,所以您会得到另一个异常。

您需要一个else子句,而不是finally来处理只有在没有异常的情况下才会发生的事情。

    try:
        file = open(filePath, 'w')
    except IOError:
        msg = "Unable to create file on disk."
        return
    else:
        file.write("Hello World!")
        file.close()

为什么是elsePython docs说:

The use of the else clause is better than adding additional code to the try clause because it avoids accidentally catching an exception that wasn’t raised by the code being protected by the try ... except statement.

换句话说,这不会捕获来自writeclose调用的IOError。这很好,因为这样做的原因就不会是“无法在磁盘上创建文件”。-这可能是另一个错误,而您的代码并没有准备好。最好不要试图处理这样的错误。

您不应该写入finally块中的文件,因为except块不会捕获任何引发的异常。

如果try块引发异常,则执行except块。无论发生什么,finally块总是执行。

此外,不需要将file变量初始化为none

except块中使用return不会跳过finally块。从本质上讲,它是不能被跳过的,这就是为什么你想把你的“清理”代码放在那里(即关闭文件)。

所以,如果你想使用try:except:finally,你应该这样做:

try:
    f = open("file", "w")
    try:
        f.write('Hello World!')
    finally:
        f.close()
except IOError:
    print 'oops!'

一种更简洁的方法是使用with语句:

try:
    with open("output", "w") as outfile:
        outfile.write('Hello World')
except IOError:
    print 'oops!'

包含

file.write("Hello World!")

finally子句中??我认为它必须放在try子句本身中。

try:
        file = open(filePath, 'w')
        file.write("Hello World!")
except IOError:
        print("Unable to create file on disk.")
finally:
        file.close()

相关问题 更多 >