error - Throw error and display message - MATLAB (original) (raw)
Throw error and display message
Syntax
Description
error([msg](#bumt5nd-msg))
throws an error and displays an error message.
error([msg](#bumt5nd-msg),[A](#bumt5nd-A1An))
displays an error message that contains formatting conversion characters, such as those used with the MATLAB® sprintf function. Each conversion character in msg
is converted to one of the valuesA
.
error([errID](#bumt5nd-msgID),___)
includes an error identifier on the exception. The identifier enables you to distinguish errors and to control what happens when MATLAB encounters the errors. You can include any of the input arguments in the previous syntaxes.
error([errorStruct](#bumt5nd-errorStruct))
throws an error using the fields in a scalar structure.
error([correction](#mw%5F56f0ff79-6e2f-4f89-8da5-017abb22fd74),___)
provides a suggested fix for the exception. You can include any of the input arguments in the previous syntaxes.
Examples
Throw Error
msg = 'Error occurred.'; error(msg)
Throw Error with Formatted Message
Throw a formatted error message with a line break. You must specify more than one input argument with error
if you want MATLAB to convert special characters (such as \n
) in the error message. Include information about the class of variablen
in the error message.
n = 7; if ~ischar(n) error('Error. \nInput must be a char, not a %s.',class(n)) end
Error. Input must be a char, not a double.
If you only use one input argument with error
, then MATLAB does not convert \n
to a line break.
if ~ischar(n) error('Error. \nInput must be a char.') end
Error. \nInput must be a char.
Throw an error with an identifier.
if ~ischar(n) error('MyComponent:incorrectType',... 'Error. \nInput must be a char, not a %s.',class(n)) end
Error. Input must be a char, not a double.
Use the MException.last
to view the last uncaught exception.
exception = MException.last
exception =
MException with properties:
identifier: 'MyComponent:incorrectType'
message: 'Error.
Input must be a char, not a double.' cause: {0x1 cell} stack: [0x1 struct]
Throw Error Using Structure
Create structure with message and identifier fields. To keep the example simple, do not use the stack field.
errorStruct.message = 'Data file not found.'; errorStruct.identifier = 'MyFunction:fileNotFound';
errorStruct =
message: 'Data file not found.'
identifier: 'MyFunction:fileNotFound'
Throw the error.
Throw Error with Suggested Fix
Create a function hello
that requires one input argument. Add a suggested input argument "world"
to the error message.
function hello(audience)
if nargin < 1
aac = matlab.lang.correction.AppendArgumentsCorrection('"world"');
error(aac, 'MATLAB:notEnoughInputs', 'Not enough input arguments.')
end
fprintf("Hello, %s!\n", audience)
end
Call the function without an argument.
Error using hello Not enough input arguments.
Did you mean:
hello("world")
Input Arguments
msg
— Information about error
text scalar containing format specification
Information about the error, specified as a text scalar containing format specification. This message displays as the error message. To format the message, use escape sequences, such as \t
or\n
. You also can use any format specifiers supported by the sprintf
function, such as %s
or%d
. Specify values for the conversion specifiers via the A1,...,An
input arguments. For more information, seeFormatting Text.
Note
You must specify more than one input argument witherror
if you want MATLAB to convert special characters (such as\t
, \n
, %s
, and %d
) in the error message.
Example: 'File not found.'
errID
— Identifier for error
text scalar containing component and mnemonic fields
Identifier for the error, specified as a text scalar containing component and mnemonic fields. Use the error identifier to help identify the source of the error or to control a selected subset of the errors in your program.
The error identifier includes one or more component fields and a mnemonic field. Fields must be separated with colon. For example, an error identifier with a component fieldcomponent
and a mnemonic fieldmnemonic
is specified as'component:mnemonic'
. The component and mnemonic fields must each begin with a letter. The remaining characters can be alphanumerics (A–Z, a–z, 0–9) and underscores. No white-space characters can appear anywhere in errID
. For more information, seeMException.
Example: 'MATLAB:singularMatrix'
Example: 'MATLAB:narginchk:notEnoughInputs'
A
— Replacement value
character vector | string scalar | numeric scalar
Value that replace the conversion specifiers in msg
, specified as a character vector, string scalar, or numeric scalar.
errorStruct
— Error reporting information
scalar structure
Error reporting information, specified as a scalar structure. The structure must contain at least one of these fields.
message | Error message. For more information, seemsg. |
---|---|
identifier | Error identifier. For more information, seeerrID. |
stack | Stack field for the error. WhenerrorStruct includes astack field,error uses it to set the stack field of the error. When you specifystack, use the absolute file name and the entire sequence of functions that nests the function in the stack frame. This character vector is the same as the one returned bydbstack('-completenames'). |
correction
— Suggested fix for this exception
matlab.lang.correction.AppendArgumentsCorrection
object | matlab.lang.correction.ConvertToFunctionNotationCorrection
object | matlab.lang.correction.ReplaceIdentifierCorrection
object
Tips
- When you throw an error, MATLAB captures information about it and stores it in a data structure that is an object of the
MException
class. You can access information in the exception object by usingtry/catch
. Or, if your program terminates because of an exception and returns control to the Command Prompt, you can useMException.last
. - MATLAB does not cease execution of a program if an error occurs within a
try
block. In this case, MATLAB passes control to thecatch
block. - If all inputs to
error
are empty, MATLAB does not throw an error.
Extended Capabilities
C/C++ Code Generation
Generate C and C++ code using MATLAB® Coder™.
Usage notes and limitations:
Has no effect in standalone code even when run-time error detection is enabled. See Generate Standalone C/C++ Code That Detects and Reports Run-Time Errors (MATLAB Coder).
Thread-Based Environment
Run code in the background using MATLAB® backgroundPool
or accelerate code with Parallel Computing Toolbox™ ThreadPool
.
This function fully supports thread-based environments. For more information, see Run MATLAB Functions in Thread-Based Environment.
GPU Arrays
Accelerate code by running on a graphics processing unit (GPU) using Parallel Computing Toolbox™.
The error
function supports GPU array input with these usage notes and limitations:
- This function accepts GPU arrays, but does not run on a GPU.
For more information, see Run MATLAB Functions on a GPU (Parallel Computing Toolbox).
Version History
Introduced before R2006a