在 Python 中自定义 FileNotFoundError 消息

Customizing a FileNotFoundError message in Python

我能够捕获异常以更改其消息。例如:

def parse(val, parse_function, errmsg):
    try:
        return parse_function(val)
    except ValueError as e:
        e.args = (errmsg,) #Overwrites the exception message
        raise e

val = input("Enter a number: ")
try:
    val = parse(val, float, "The input is not a number")
except ValueError as e:
    print(e) #if executed, prints "The input is not a number"

但是,如果我使用 FileNotFoundException 执行此操作,则它不起作用:

def do_stuff(filename):
    try:
        with open(filename, "r") as file:
            pass
            #do stuff with the file
    except FileNotFoundError as e:
        e.args = ("The file doesn't exist",) #Overwrites the exception message
        raise e

try:
    do_stuff("inexistent_file_name")
except FileNotFoundError as e:
    print(e) #Doesn't print "The file doesn't exist", prints "[Errno 2] No such file or directory: 'inexistent_file_name'"

这是为什么?以及如何自定义 FileNotFoundException 消息?

def do_stuff(filename):
    try:
        with open(filename, "r") as file:
            pass
            #do stuff with the file
    except FileNotFoundError as e:
        e.args = ("The file doesn't exist",) #Overwrites the exception message
        raise e

try:
    do_stuff("inexistent_file_name")
except FileNotFoundError as e:
    print(e.args) 

似乎 FileNotFoundError__str__ 方法(在 print 函数中调用)不只是 return args。相反,__str__ 正在从 errnostrerrorfilename 组成一个自定义字符串(可能看起来像这样:f"[Errno {errno}] {strerror}: '{filename}'")。

因此,您可能需要调整 errnostrerrorfilename 而不是 args 来修改错误消息,例如:

except FileNotFoundError as e:
    e.strerror = "The file doesn't exist"
    raise e

这将打印 "[Errno 2] The file doesn't exist: 'inexistent_file_name'"