assert

Generate error when condition is violated

Syntax

assert(expression)
assert(expression, 'msgString')
assert(expression, 'msgString', value1, value2, ...)
assert(expression, 'msgIdent', 'msgString', value1, value2, ...)

Description

assert(expression) evaluates expression and, if it is false, generates an exception. Depending on how the program has been designed to respond to the assertion failure, MATLAB® either enters a catch block to handle the condition, or exits the program.

assert(expression, 'msgString') evaluates expression and, if it is false, generates an exception and displays the string contained in msgString. This string must be enclosed in single quotation marks. When msgString is the last input to assert, the MATLAB software displays it literally, without performing any substitutions on the characters in msgString.

assert(expression, 'msgString', value1, value2, ...) evaluates expression and, if it is false, generates an exception and displays the formatted string contained in msgString. The msgString string can include escape sequences such as \t or \n, as well as any of the C language conversion operators supported by the sprintf function (e.g., %s or %d). Additional arguments value1, value2, etc. provide values that correspond to and replace the conversion operators.

See Formatting Strings in the MATLAB Programming Fundamentals documentation for more detailed information on using string formatting commands.

MATLAB makes substitutions for escape sequences and conversion operators in msgString in the same way that it does for the sprintf function.

assert(expression, 'msgIdent', 'msgString', value1, value2, ...) evaluates expression and, if it is false, generates an exception and displays the formatted string msgString, also tagging the error with the message identifier msgIdent. See Message Identifiers in the MATLAB Programming Fundamentals documentation for information.

Examples

This function tests input arguments using assert:

function write2file(varargin)
min_inputs = 3;
assert(nargin >= min_inputs, ...
  'You must call function %s with at least %d inputs', ...
  mfilename, min_inputs)

infile = varargin{1};
assert(ischar(infile), ...
      'First argument must be a filename.')
assert(exist(infile)~=0, 'File %s not found.', infile)

fid = fopen(infile, 'w');
assert(fid > 0, 'Cannot open file %s for writing', infile)

fwrite(fid, varargin{2}, varargin{3});

Was this topic helpful?