sequential try catch end block for matlab

前端 未结 2 1937
北海茫月
北海茫月 2020-12-21 03:45

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

2条回答
  •  旧巷少年郎
    2020-12-21 03:50

    One option is 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
    

    And here's the output this generates, showing that functions are still evaluated even after one throws an error:

    1
    2
    Error with function 3.
    4
    

    The above example works for the case when you have individual lines of code you want to evaluate sequentially, but you can't fit multiple lines into an anonymous function. In this case, I would go with nested functions if they have to access variables in the larger workspace or local functions if they can operate independently. Here's an example with nested functions:

    function fcn1
      b = a+1;     % Increments a
      fprintf('%d\n', b);
    end
    function fcn2
      error();     % Errors
    end
    function fcn3
      b = a.^2;    % Squares a
      fprintf('%d\n', b);
    end
    
    a = 2;
    fcnList = {@fcn1 @fcn2 @fcn3};
    
    for fcnIndex = 1:numel(fcnList)
      try
        fcnList{fcnIndex}();
      catch
        fprintf('Error with function %d.\n', fcnIndex);
      end
    end
    

    And the output:

    3
    Error with function 2.
    4
    

提交回复
热议问题