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
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.
Construct an MException object to represent the error. Add a message identifier string and error message string to the object when calling the constructor.
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 method for this.
Use the throw or throwAsCaller function to have the MATLAB® software 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.
This example illustrates throwing an exception using the steps just described:
Create an array, and an index into it with a logical array.
A = [13 42; 7 20]; idx = [1 0 1; 0 1 0];
Create an exception that provides general information about an error. Test the index array and add exceptions with more detailed information about the source of the failure.
% 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); % 3) Store any information contributing to the error. try assert(islogical(idx),'MYFUN:notLogical',... 'Indexing array is not logical.') catch causeException baseException = addCause(baseException,causeException); end if any(size(idx) > size(A)) msgID = 'MYFUN:incorrectSize'; msg = 'Indexing array is too large.'; causeException2 = MException(msgID,msg); baseException = addCause(baseException,causeException2); end % 4) Throw the exception to stop execution and display an error % message. throw(baseException) end
Unable to index into array. Caused by: Indexing array is not logical. Indexing array is too large.