Repeat Try/Catch loop?

136 visualizaciones (últimos 30 días)
Tom
Tom el 22 de Jul. de 2013
I have code that sometimes results in an error, and sometimes not. I'd like to have the code run, and then if an error occurs try again until there is no error. Could this be done using a try/catch loop? I.e. the catch statement would tell the program to repeat the try statements? I'm not sure how to implement this.
Thanks!

Respuesta aceptada

Evan
Evan el 22 de Jul. de 2013
Editada: Evan el 22 de Jul. de 2013
You could embed your try/catch statements in a while loop, then check a condition at the beginning each iteration to see if the previous iteration ended in an error.
This could either be done through dealing with the MException object itself or just through setting a counter both inside the catch portion and outside the try/catch statement. When the two counters don't match up, you know that you have just had a successful run.
count = 0;
err_count = 0;
while count == err_count
try
i = randi(9);
if i ~= 7
error
end
catch MyErr
err_count = err_count + 1;
end
count = count + 1;
end

Más respuestas (1)

Daniel Shub
Daniel Shub el 22 de Jul. de 2013
Editada: Daniel Shub el 22 de Jul. de 2013
You could do something like
function varargout = myfunc(varargin)
try
thingThatSometimesCrashes;
catch
[vargout{1:nargout}] = myfunc(varargin{:})
end
end
This is a recursive loop. If thingThatSometimesCrashes crashes too many times in a row, the function will exceed the recursion limit and still crash. You could instead do a loop with a flag
function varargout = myfunc(varargin)
myflag = true;
while myflag
try
thingThatSometimesCrashes;
myflag = false;
end
end
end

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