Try catch to load files
12 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Ana Gabriela Guedes
el 18 de Jul. de 2021
Comentada: Ana Gabriela Guedes
el 19 de Jul. de 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 comentarios
Respuesta aceptada
Walter Roberson
el 18 de Jul. de 2021
Editada: Walter Roberson
el 18 de Jul. de 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
Más respuestas (1)
Image Analyst
el 18 de Jul. de 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.
Ver también
Categorías
Más información sobre Audio and Video Data en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!