try - Execute statements and catch resulting errors - MATLAB (original) (raw)
Execute statements and catch resulting errors
Syntax
try
statements
catch exception
statements
end
Description
try _`statements`_, catch _`statements`_ end
executes 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 catch
block, which contains your error handling statements.
exception
is an MException
object that allows you to identify the error. The catch
block assigns the current exception object to the variable in exception
.
Both try
and catch
blocks can contain nested try/catch
statements.
Examples
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.
Use 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 function, 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 notaFunction
results in an error. If you use try
and catch
, this code catches any exception and repackages it as a warning, allowing MATLAB to continue executing subsequent commands.
Use try/catch
to handle different types of errors in different ways.
- If the function
notaFunction
is undefined, issue a warning instead of an error and assign the output a value ofNaN
. - If
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 of0
. - 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.
Tips
- You cannot use multiple
catch
blocks within atry
block, but you can nest completetry/catch
blocks. - Unlike some other languages, MATLAB does not allow the use of a
finally
block withintry/catch
statements.
Extended Capabilities
Version History
Introduced before R2006a
The try
block shows improved performance when the statements within the block run error-free. For example, this code is approximately 6x faster than in the previous release.
function testTryPerformance x = 1; for i = 1:1e8 try x = x * i; catch warning("Assignment was not successful.") x = 1; end end end
The approximate execution times are:
R2021b: 2.3 s
R2022a: 0.4 s
The code was timed on a Windows® 10, Intel® Xeon® CPU E5-1650 v4 @ 3.60 GHz test system using thetimeit
function.
timeit(@testTryPerformance)