Try catch to load files
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Ana Gabriela Guedes
le 18 Juil 2021
Commenté : Ana Gabriela Guedes
le 19 Juil 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 commentaires
Réponse acceptée
Walter Roberson
le 18 Juil 2021
Modifié(e) : Walter Roberson
le 18 Juil 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
Plus de réponses (1)
Image Analyst
le 18 Juil 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.
Voir également
Catégories
En savoir plus sur Audio and Video Data dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!