How do I force the next loop iteration if error occurs within the loop?
Show older comments
I have a loop that is supposed to run a very long time that starts with a webread command. Sometimes there is something wrong with the page it’s trying to read which causes the script to stop and display the error. From what I understand you can put the command within a “try” command to continue despite the error like this:
try
webread(‘www.something that could or could not generate an error.com’)
catch
continue
end
First of all; is that the correct way of writing it or would I need to specify anything more after writing “catch”? And can I modify this so that instead of continuing the script it restarts it from the next iteration in the loop? If I write:
for i=1:100
try
webread(‘www.something that could or could not generate an error.com’)
catch
end %I want this to cause the loop to jump up to the next value of i and restart the loop
end
end
Matlab won’t understand what I mean with my double end statement. Is there some other way of doing this? I want my script to always ignore errors and just try again with a new iteration.
Accepted Answer
More Answers (1)
Walter Roberson
on 18 Jun 2015
It is recommended that you follow "catch" by the name of a variable to receive the error structure, such as
catch EX
"continue" already means "start the next execution of the loop without doing the rest of the body of the loop". It does not mean "ignore the error and keep going with the code". If you wanted to keep going with the code you would use
try
...
catch
end
with no "continue".
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!