python - 在 Python 中自定义 FileNotFoundError 消息

标签 python exception customization filenotfoundexception

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

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 消息?

最佳答案

看起来FileNotFoundError__str__方法(在print函数中调用)并不简单地返回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]文件不存在:'inexistent_file_name'”

关于python - 在 Python 中自定义 FileNotFoundError 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58836780/

相关文章:

swift - “ fatal error :在展开可选值时意外发现nil”是什么意思?

c# - 如何捕获从延续抛出的未处理异常?

java - 如何修改hibernate生成的SQL查询?

compiler-construction - 如何在 IntelliJ IDEA 中为某些文件类型定义自定义编译器?

python - "Flatten"list 包含lists of lists to lists of lists

python - 如何对字符串进行数学运算?

Python - 制作脚本来操作 Windows 文件路径但在 Linux 上运行

python - 如何对 pandas groupby 列中的特定值进行分组?

c# - 异常消息是否应该全局化

android - 在 API 12 中更改编辑文本光标颜色