Try catch to load files
10 views (last 30 days)
Show older comments
Ana Gabriela Guedes
on 18 Jul 2021
Commented: Ana Gabriela Guedes
on 19 Jul 2021
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 Comments
Accepted Answer
Walter Roberson
on 18 Jul 2021
Edited: Walter Roberson
on 18 Jul 2021
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
More Answers (1)
Image Analyst
on 18 Jul 2021
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.
See Also
Categories
Find more on Audio and Video Data in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!