MATLAB Examples

Contents

Throw an error using built-in "error".

Retrieve it using lasterr. Note the additional line in the error message.

try
    fn = @() error('ErrorAPI:TestScript1','Error thrown using built-in function "error"');
    fn();
catch
    s = lasterror;
    disp(['Error code was: ' s.identifier]);
    errordlg(lasterr,'Demo Application','modal');
end
Error code was: ErrorAPI:TestScript1

Throw an error using xError.

Retrieve it using xLastErr. Note that the additional line is absent from the message.

try
    fn = @() xError('ErrorAPI:TestScript2','Error thrown using "xError"');
    fn();
catch
    s = xLastError;
    disp(['Error code was: ' s.identifier]);
    errordlg(xLastErr,'Demo Application','modal');
end
Error code was: ErrorAPI:TestScript2

Cause another function to throw an error.

Retrieve it using xLastErr. The additional line is present again, but note that even though this error did not go through xError, it is still picked up correctly by xLastErr.

try
    bar('bar doesn''t accept strings');
catch
    s = xLastError;
    disp(['Error code was: ' s.identifier]);
    errordlg(xLastErr,'Demo Application','modal');
end
Error code was: MATLAB:bar:NoDataInputs

Provoke a built-in error.

This doesn't always get the additional line added to it, but then it's the sort of error we try to avoid anyway.

try
    asdflkjh
catch
    s = xLastError;
    disp(['Error code was: ' s.identifier]);
    errordlg(xLastErr,'Demo Application','modal');
end
Error code was: MATLAB:UndefinedFunction