为什么不能通过try-except处理“ io.UnsupportedOperation”错误

时间:2019-05-25 14:01:24

标签: python error-handling

运行以下代码将引发io.UnsupportedOperation错误,因为该文件以“写入”模式打开-

with open("hi.txt", "w") as f:
    print(f.read())

输出为-

io.UnsupportedOperation: not readable

因此,我们可以尝试通过执行此操作来掩盖-

try:
    with open("hi.txt", "w") as f:
        print(f.read())
except io.UnsupportedOperation:
    print("Please give the file read permission")

输出-

NameError: name 'io' is not defined

即使删除“ io”。吐出相同的错误-

try:
    with open("hi.txt", "w") as f:
        print(f.read())
except UnsupportedOperation:
    print("Please give the file read permission")

输出-

NameError: name 'UnsupportedOperation' is not defined

为什么不起作用? “ io.UnsupportedOperation”不是错误吗?

1 个答案:

答案 0 :(得分:2)

在模块io中找到io.UnsupportedError。因此,在使用它之前,我们需要导入io

import io

然后,当我们在tryexcept子句中测试错误时,可以使用io.UnsupportedError。 这给了我们:

import io

try:
    with open("hi.txt", "w") as f:
        print(f.read())
except io.UnsupportedOperation as e:
    print(e)

,或者如果您仅使用io模块检查此特定错误。

from io import UnsupportedError

try:
    with open("hi.txt", "w") as f:
        print(f.read())
except UnsupportedOperation as e:
    print(e)