Borrar filtros
Borrar filtros

repeat the iteration with an error using try/catch

11 visualizaciones (últimos 30 días)
Mos_bad
Mos_bad el 3 de Abr. de 2020
Editada: James Tursa el 4 de Abr. de 2020
I wrote a nested for loop to exexcute a huge number of iterations. However, sometimes an error stops the program. I want to repeat the iEv'th iteration in case an error occurs and then continue to next iteration. Please see below the code and let me know if it should be modified.
for iTcm=1:nTcm
for iScen=1:nScen
for iEv=1:nEv
try
MyProgramHere
catch ME
disp(ME);
fprintf('Retrying the program...\n');
end
end
end
end

Respuesta aceptada

James Tursa
James Tursa el 3 de Abr. de 2020
Editada: James Tursa el 3 de Abr. de 2020
Maybe this construct does what you want
while( true )
try
MyProgramHere
break
catch ME
disp(ME);
fprintf('Retrying the program...\n');
end
end
  3 comentarios
Mos_bad
Mos_bad el 3 de Abr. de 2020
This code didn't work either. Any help?
James Tursa
James Tursa el 3 de Abr. de 2020
Editada: James Tursa el 4 de Abr. de 2020
No. I meant exactly what I wrote, without this line:
iEv = iEv - 1; % delete this line
By getting rid of this line, it will keep repeating the same iteration indefinitely until it passes. iEv doesn't change until you do the iteration successfully. If you want a limit on the number of tries before you generate an error then additional code would need to be added.

Iniciar sesión para comentar.

Más respuestas (1)

darova
darova el 3 de Abr. de 2020
Editada: darova el 3 de Abr. de 2020
My proposition
for iTcm=1:nTcm
for iScen=1:nScen
iEv = 0;
while iEv <= nEv
iEv = iEv + 1;
try
MyProgramHere
catch ME
iEv = iEv-1;
disp(ME);
fprintf('Retrying the program...\n');
end
end
end
end
  4 comentarios
darova
darova el 3 de Abr. de 2020
What about this. I improved my code
Mos_bad
Mos_bad el 3 de Abr. de 2020
With the improved code, when the iEv count reaches to nEv, the program control goes immediately to the catch block. So the program stops without going to (iScen+1)th iteration.

Iniciar sesión para comentar.

Categorías

Más información sobre Loops and Conditional Statements 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!

Translated by