Try catch to load files
12 次查看(过去 30 天)
显示 更早的评论
Hi!! I'm writing a program in which I have to load multiple files within a cycle and work with them.
The program calls the different files each time it runs the cycle but I would luke to know what is the best way to handle an error when the file it is trying to load doesn't exist so it just continues to the next one, eliminating the need to stop the program run.
I thought of doing this with a try catch but couldn't find exactly how in the documentation
0 个评论
采纳的回答
Walter Roberson
2021-7-18
编辑:Walter Roberson
2021-7-18
cminfo = which('cameraman.tif');
cmdir = fileparts(cminfo)
dinfo = dir(cmdir);
dinfo([dinfo.isdir]) = [];
filenames = fullfile({dinfo.folder}, {dinfo.name});
nfiles = length(filenames);
results = cell(nfiles, 1);
for K = 1 : nfiles
thisfile = filenames{K};
try
%demonstration processing
fileinfo = imfinfo(thisfile);
results{K} = fileinfo;
catch ME
fprintf('not image file: "%s"\n', thisfile);
continue
end
end
results
更多回答(1 个)
Image Analyst
2021-7-18
The best way is to follow the FAQ:
You create a loop where you either only have files that exist (if you use the dir() function), or you check if the file exists with exist() or isfile(), and then you'll only process the files that do exist so no error ever gets thrown and there is no need to put
try
% Try to open file with whatever function you want.
catch ME
% Error opening the file, like it doesn't exist or you don't have permission.
continue; % Skip to bottom of for loop but continue interating.
end
but again, the above code is not recommended and I recommend you do it like in the FAQ.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Audio and Video Data 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!