%% Handle Errors in Future Variables
% When computations for future variables result in an error, by default, afterEach does not evaluate its function on the elements that failed. If you want to handle any errors, for example, you have a user interface that you want to update, you can use the name-value pair PassFuture. When set to true, the future variable is passed to the callback function. You can call fetchOutputs on it, process the outputs, and handle any possible errors.
% Send computations to the workers using parfeval. With default preferences, parfeval creates a parpool automatically if there is not one already created. If your parfeval computations result in an error, the future variable errors, and its Error property reflects it.

errorFuture = parfeval(@(n) randn(n), 0, 0.5);
wait(errorFuture);
errorFuture.Error

% If you use afterEach on that future, the callback function is not evaluated on those elements in the future that errored. In the code below, the msgbox is not executed because the future errors.

afterEach(errorFuture, @() msgbox('Operation completed'), 0);

% To handle futures that result in errors, use the name-value pair PassFuture when calling afterEach. The future variable is passed to the callback function instead of its outputs. Call fetchOutputs on the future variable, and process its outputs. If the future results in an error, fetchOutputs throws an error that you can catch and handle. The following code shows an error dialog box.

afterEach(errorFuture, @handleError, 0, 'PassFuture', true);

%

function handleError(f)
    try
        output = fetchOutputs(f);
        % Do something with the output
    catch
        errordlg('Operation failed');
    end
end

% Copyright 2020 The MathWorks, Inc.