Navigation

Operators and Keywords

Function List:

C++ API

: error (template, …)
: error (id, template, …)

Display an error message and stop m-file execution.

Format the optional arguments under the control of the template string template using the same rules as the printf family of functions (see ‘Formatted Output’) and print the resulting message on the stderr stream. The message is prefixed by the character string ‘error: ’.

Calling error also sets Octave’s internal error state such that control will return to the top level without evaluating any further commands. This is useful for aborting from functions or scripts.

If the error message does not end with a newline character, Octave will print a traceback of all the function calls leading to the error. For example, given the following function definitions:

function f () g (); end
function g () h (); end
function h () nargin == 1 ||error ("nargin != 1"); end

calling the function f will result in a list of messages that can help you to quickly find the exact location of the error:

f ()
error: nargin != 1
error: called from:
error:   h at line 1, column 27
error:   g at line 1, column 15
error:   f at line 1, column 15

If the error message ends in a newline character, Octave will print the message but will not display any traceback messages as it returns control to the top level. For example, modifying the error message in the previous example to end in a newline causes Octave to only print a single message:

function h () nargin == 1 ||error ("nargin != 1\n"); end
f ()
error: nargin != 1

A null string ("") input to error will be ignored and the code will continue running as if the statement were a NOP. This is for compatibility with MATLAB. It also makes it possible to write code such as

err_msg = "";
if (CONDITION 1)
 err_msg = "CONDITION 1 found";
elseif (CONDITION2)
 err_msg = "CONDITION 2 found";
…
endif
error (err_msg);

which will only stop execution if an error has been found.

Implementation Note: For compatibility with MATLAB, escape sequences in template (e.g., "\n" => newline) are processed regardless of whether template has been defined with single quotes, as long as there are two or more input arguments. To disable escape sequence expansion use a second backslash before the sequence (e.g., "\\n") or use the regexptranslate function.

See also: warning, lasterror.

Package: octave