Python 3.x FileNotFound错误消息未打印
FileNotFoundError中的消息不会打印,ValueError可以正常工作,下面是实现此功能的代码:Python 3.x FileNotFound错误消息未打印,python-3.x,file,exception,filenotfoundexception,try-except,Python 3.x,File,Exception,Filenotfoundexception,Try Except,FileNotFoundError中的消息不会打印,ValueError可以正常工作,下面是实现此功能的代码: try: with open(path) as f: if header==True: next(f) for line in f: try: cnt += 1 a
try:
with open(path) as f:
if header==True:
next(f)
for line in f:
try:
cnt += 1
a = line.count("|") + 1
if a == fields:
b.append(line)
yield b
else:
#raise ValueError(f"'{tail}' has {a} fields on line {cnt} but expected {fields}")
raise ValueError("Hello")
except ValueError as v:
print(v)
continue
raise FileNotFoundError("Wrong file or file path")
except FileNotFoundError as e:
print(e)
下面的输出打印值错误消息,但不打印FileNotFoundError:
[Errno 2] No such file or directory: 'C://Users/Documents/abcde.txt'
FileNotFoundError:
[Errno 2] No such file or directory: 'C://Users/Documents/abcde.txt'
值错误:
['bob|1|23\n']
Hello
FileNotFoundError
异常在语句中引发,open(path)为f:
。该控件将立即传递给除FileNotFoundError外的部分,作为e:
打印异常。您的代码raise FileNotFoundError(“错误的文件或文件路径”)
未被执行。感谢您注意到,是否有方法纠正此问题,与VALUERROR不同,此处没有其他语句添加raise异常如果该异常已由with
语句引发,您为什么要手动引发该异常?