I'd like to run several lines of code, but I'm unsure if any line will throw an error. If an error occurs however, I'd like the script to ignore that line and continue on.
One choice would be to have a try-catch-end
block, that skips over a block of code that may throw errors. However, as soon as an error occurs, the rest of the code after the error in the try-statement is not executed.
TL;TR: Do I have another choice than writing a try-catch-end
block for every individual line in the following example code?
Example code:
try
disp('1st line');
disp('2nd line');
PRODUCE_ERROR; %throws an error, variable/function does not exist
disp('3rd line'); %%%%%
disp('4th line'); % these lines I would like to keep executing
disp('5th line'); %%%%%
catch
disp('something unexpected happened');
end
Output:
1st line
2nd line
something unexpected happened
Output that would be preferred:
1st line
2nd line
something unexpected happened
3rd line
4th line
5th line
related: Why should I not wrap every block in "try"-"catch"?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…