Issue Warnings and Errors
In this section...
“Issue Warnings” on page 26-30
“Throw Errors” on page 26-30
“Add Run-Time Parameters to Your Warnings and Errors” on page 26-31
“Add Identifiers to Warnings and Errors” on page 26-32
Issue Warnings
You can issue a warning to flag unexpected conditions detected when running a program.
The warning function prints a warning message to the command line. Warnings differ
from errors in two significant ways:
- Warnings do not halt the execution of the program.
- You can suppress any unhelpful MATLAB warnings.
Use the warning function in your code to generate a warning message during execution.
Specify the message as the input argument to the warning function:
warning('Input must be text')
For example, you can insert a warning in your code to verify the software version:
function warningExample1
if ~strncmp(version, '7', 1)
warning('You are using a version other than v7')
end
Throw Errors
You can throw an error to flag fatal problems within the program. Use the error function
to print error messages to the command line. After displaying the message, MATLAB
stops the execution of the current program.
For example, suppose you construct a function that returns the number of combinations
of k elements from n elements. Such a function is nonsensical if k > n; you cannot
choose 8 elements if you start with just 4. You must incorporate this fact into the function
to let anyone using combinations know of the problem:
26 Error Handling