error

Throws an error, stopping the running code unless it is caught.

Category: Programming > Functions

Syntax

error(msg)

Throws an error with the message msg.

error(msg, A1, ..., An)

Formats the message like sprintf before throwing.

error(id, msg, A1, ..., An)

Also sets the message identifier id, such as 'MyPkg:badInput'.

error(ME)

Throws an existing MException object, or a struct with the fields message and identifier.

Description

error is how code reports a situation it cannot continue from. An uncaught error stops the script and prints the message; inside try ... catch, the caught object err has err.message, err.identifier and err.stack. Identifiers let callers react to a specific failure with strcmp(err.identifier, 'MyPkg:badInput') instead of matching message text.

A single argument that looks like an identifier, as in error('Result:bad'), is treated as the message and leaves the identifier empty; supply a message after the identifier to set both.

Input arguments

msg
Message text. Format fields and escape sequences such as \n are processed only when extra arguments follow.
id
Identifier made of parts joined by colons, no spaces, with at least one colon.
A1, ..., An
Values for the format fields of msg.
ME
An MException object or a struct.

Example

Catching an error with an identifier

try
    error('Demo:tooBig', 'Value %d is larger than %d', 12, 10);
catch err
    disp(err.identifier)
    disp(err.message)
end
Output
Demo:tooBig
Value 12 is larger than 10

See also

warning assert MException lasterr