| Products & Services | Solutions | Academia | Support | User Community | Company |
| Download Product Updates | | | Get Pricing | | | Trial Software |
| R2010b Documentation → MATLAB |
| Contents | Index |
| Learn more about MATLAB |
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 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:
function check_results(resultsArr, dataFile) minValue = 0.09; maxValue = 2.14; % 1) Detect the error. if any(resultsArr < minValue) || any(resultsArr > maxValue) % 2) Construct an MException object to represent the error. err = MException('ResultChk:OutOfRange', ... 'Resulting value is outside expected range'); fileInfo = dir(dataFile); % 3) Store any information contributing to the error. if datenum(fileInfo.date) < datenum('Oct09','mmmyy') errCause = MException('ResultChk:BadInput', ... 'Input file %s is out of date.', dataFile); err = addCause(err, errCause); end % 4) Throw the exception to stop execution and display an error message. throw(err) end
If the program detects the OutOfRange condition, the throw(err) statement throws an exception at the end. If the BadInput condition is also detected, the program also displays this as the cause:
resultsArr = [1.63, 2.05, 0.91, 2.16, 1.5, 2.11 0.72];
check_results(resultsArr, 'run33.dat')
??? Error using ==> check_results at 12
Resulting value is outside expected range
Caused by:
Input file run33.dat is out of date.
![]() | Capturing Information About the Error | Responding to an Exception | ![]() |

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.
| © 1984-2010- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |