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

Arn*_*rnb 1 python error-handling

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

with open("hi.txt", "w") as f:
    print(f.read())
Run Code Online (Sandbox Code Playgroud)

输出是 -

io.UnsupportedOperation: not readable
Run Code Online (Sandbox Code Playgroud)

所以,我们可以尝试通过这样做来掩盖这一点——

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

输出 -

NameError: name 'io' is not defined
Run Code Online (Sandbox Code Playgroud)

甚至删除“io”。吐出同样的错误 -

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

输出 -

NameError: name 'UnsupportedOperation' is not defined
Run Code Online (Sandbox Code Playgroud)

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

小智 5

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

import io

那么当我们测试 try except 子句中的错误时,我们可以使用 io.UnsupportedError。这给了我们:

import io

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

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

from io import UnsupportedError

try:
    with open("hi.txt", "w") as f:
        print(f.read())
except UnsupportedOperation as e:
    print(e)
Run Code Online (Sandbox Code Playgroud)