为什么 Matlab `fopen` 不抛出异常?
Why doesn't Matlab `fopen` throw an exception?
为什么当文件名或路径不存在时fopen
不抛出异常?
in_path = 'pqlcnaf8765mlr9f6lf2;
try
in_file_id = fopen(in_path,'r');
catch
error('Problem with input file.')
end
in_path
不存在。调用 returns in_file_id
的值为 -1
,但没有抛出异常。有人知道为什么吗?
它不是为了抛出异常而设计的,如文档所述:
If fopen cannot open the file, it returns -1.
您需要设计代码以引发您想要的异常:
in_path = 'pqlcnaf8765mlr9f6lf2;
in_file_id = fopen(in_path,'r');
if in_file_id == -1
error('Problem with input file.')
end
编辑
回复:第一条评论中的 link -> 显示了如何处理 try catch
块。由于 fread
行,它会引发错误。您可以在代码中执行相同的操作:
try
in_file_id = fopen(in_path,'r');
fread(in_file_id);
catch
error('Problem with input file.')
end
话虽如此,我认为 link 不是一个如何处理不存在的文件的好例子。
为什么当文件名或路径不存在时fopen
不抛出异常?
in_path = 'pqlcnaf8765mlr9f6lf2;
try
in_file_id = fopen(in_path,'r');
catch
error('Problem with input file.')
end
in_path
不存在。调用 returns in_file_id
的值为 -1
,但没有抛出异常。有人知道为什么吗?
它不是为了抛出异常而设计的,如文档所述:
If fopen cannot open the file, it returns -1.
您需要设计代码以引发您想要的异常:
in_path = 'pqlcnaf8765mlr9f6lf2;
in_file_id = fopen(in_path,'r');
if in_file_id == -1
error('Problem with input file.')
end
编辑
回复:第一条评论中的 link -> 显示了如何处理 try catch
块。由于 fread
行,它会引发错误。您可以在代码中执行相同的操作:
try
in_file_id = fopen(in_path,'r');
fread(in_file_id);
catch
error('Problem with input file.')
end
话虽如此,我认为 link 不是一个如何处理不存在的文件的好例子。