0

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.

WJA
  • 6,676
  • 16
  • 85
  • 152
  • @gnovice I do not see any benefit of the answer as provided in the link you forwarded to me. I am looking for a clean solution which does not require me to put a `try` or `@()` at the beginning of each line. I do not see any benefit of the answer.. you might as well do what I did above. – WJA Jan 27 '18 at 11:57
  • 1
    It's exactly the same question, hence it's a duplicate question. I'll try to add another answer there, there are other solutions. – Cris Luengo Jan 28 '18 at 05:56
  • I have added a different solution to the other question. I hope it's useful! – Cris Luengo Jan 28 '18 at 06:44

0 Answers0