Try catch to load files
12 visualizzazioni (ultimi 30 giorni)
Mostra commenti meno recenti
Ana Gabriela Guedes
il 18 Lug 2021
Commentato: Ana Gabriela Guedes
il 19 Lug 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 Commenti
Risposta accettata
Walter Roberson
il 18 Lug 2021
Modificato: Walter Roberson
il 18 Lug 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
Più risposte (1)
Image Analyst
il 18 Lug 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.
Vedere anche
Categorie
Scopri di più su Audio and Video Data in Help Center e File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!