Throw an Exception
When your program detects a fault that will keep it from completing as expected or will
generate erroneous results, you should halt further execution and report the error by
throwing an exception. The basic steps to take are:
(^1) Detect the error. This is often done with some type of conditional statement, such as
an if or try/catch statement that checks the output of the current operation.
(^2) Construct an MException object to represent the error. Add a message identifier and
error message to the object when calling the constructor.
(^3) If there are other exceptions that may have contributed to the current error, you can
store the MException object for each in the cause field of a single MException
that you intend to throw. Use the addCause function for this.
(^4) If there is fix that can be suggested for the current error, you can add it to the
Correction field of the MException that you intend to throw. Use the
addCorrection function for this.
(^5) Use the throw or throwAsCaller function to have MATLAB issue the exception. At
this point, MATLAB stores call stack information in the stack field of the
MException, exits the currently running function, and returns control to either the
keyboard or an enclosing catch block in a calling function.
Suggestions on How to Throw an Exception
This example illustrates throwing an exception using the steps just described.
Create a function, indexIntoArray, that indexes into a specified array using a specified
index. The function catches any errors that MATLAB throws and creates an exception that
provides general information about the error. When it catches an error, it detects whether
the error involves the number of inputs or the specified index. If it does, the function adds
additional exceptions with more detailed information about the source of the failure, and
suggests corrections when possible.
function indexIntoArray(A, idx)
% 1) Detect the error.
try
A(idx)
catch
% 2) Construct an MException object to represent the error.
msgID = 'MYFUN:BadIndex';
msg = 'Unable to index into array.';
baseException = MException(msgID,msg);
26 Error Handling