I am trying to do a Try/Catch statement but without skipping all the lines after the line where the error occurs.
To illustrate, let's say we have this:
A = 1;
B = 2+C; % error will be triggered on this line
D = 5; % next line to be executed after a potential error
The error will be triggered on Line 2. However, I want that the error does not terminate the script and continues with Line 3 and so on.
Obviously we could solve this by doing the following:
try A = 1; catch; end
try B = 2+C; catch; end
try D = 5; catch; end
However, this will require me to put all these statements for all the lines. As I have a large file with over 500 lines of code, I would like to avoid this. Is there a way to define somehow at the beginning a conditional try, that keeps going on to the next line after an error?
Further comments
This answer provides a solution to put each section of code in a function and iterate over a cell array of the function handles. Here's an example with a list of anonymous functions:
fcnList = {@() disp('1'); ...
@() disp('2'); ...
@() error(); ... % Third function throws an error
@() disp('4')};
for fcnIndex = 1:numel(fcnList)
try
fcnList{fcnIndex}(); % Evaluate each function
catch
fprintf('Error with function %d.\n', fcnIndex); % Display when an error happens
end
end
However, I do not see any benefit of adding a @() in front of each line of the code, instead of simply putting it in a try (...); end on each line (the latter is even cleaner than the complex solution as proposed in the other answer). I really would like to wrap it in something that then knows that it should skip lines.