我能够捕获异常来更改其消息。例如:
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__
由 errno
、strerror
和 filename
组成自定义字符串(可能看起来像这样: f"[Errno {errno}] {strerror}: '{filename}'"
)。
因此,您可能需要调整 errno
、strerror
和 filename
而不是 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/