Execute statements and catch resulting errors
the statements in the
try block and catches resulting
errors in the
catch block. This approach allows
you to override the default error behavior for a set of program statements.
If any statement in a
try block generates an error,
program control goes immediately to the
which contains your error handling statements.
exception is an
that allows you to identify the error. The
assigns the current exception object to the variable in
can contain nested
Create two matrices that you cannot concatenate vertically.
A = rand(3); B = ones(5); C = [A; B];
Error using vertcat Dimensions of matrices being concatenated are not consistent.
try/catch to display more information
about the dimensions.
try C = [A; B]; catch ME if (strcmp(ME.identifier,'MATLAB:catenate:dimensionMismatch')) msg = ['Dimension mismatch occurred: First argument has ', ... num2str(size(A,2)),' columns while second has ', ... num2str(size(B,2)),' columns.']; causeException = MException('MATLAB:myCode:dimensions',msg); ME = addCause(ME,causeException); end rethrow(ME) end
Error using vertcat Dimensions of matrices being concatenated are not consistent. Caused by: Dimension mismatch occurred: First argument has 3 columns while second has 5 columns.
If matrix dimensions do not agree, MATLAB® displays more information about the mismatch. Any other errors appear as usual.
Catch any exception generated by calling the nonexistent
notaFunction. If there is an exception,
issue a warning and assign the output a value of 0.
try a = notaFunction(5,6); catch warning('Problem using function. Assigning a value of 0.'); a = 0; end
Warning: Problem using function. Assigning a value of 0.
By itself, the call to
in an error. If you use
this code catches any exception and repackages it as a warning, allowing MATLAB to
continue executing subsequent commands.
try/catch to handle different types
of errors in different ways.
If the function
undefined, issue a warning instead of an error and assign the output
a value of
notaFunction.m exists, but is
a script instead of a function, issue a warning instead of an error,
run the script, and assign the output a value of
If MATLAB throws an error for any other reason, rethrow the exception.
try a = notaFunction(5,6); catch ME switch ME.identifier case 'MATLAB:UndefinedFunction' warning('Function is undefined. Assigning a value of NaN.'); a = NaN; case 'MATLAB:scriptNotAFunction' warning(['Attempting to execute script as function. '... 'Running script and assigning output a value of 0.']); notaFunction; a = 0; otherwise rethrow(ME) end end
Warning: Function is undefined. Assigning a value of NaN.