lasterr

Last error message

    Note:   lasterr will be removed in a future version. You can obtain information about any error that has been generated by catching an MException. See Capture Information About Exceptions in the Programming Fundamentals documentation.

Syntax

msgstr = lasterr
[msgstr, msgid] = lasterr
lasterr('new_msgstr')
lasterr('new_msgstr', 'new_msgid')
[msgstr, msgid] = lasterr('new_msgstr', 'new_msgid')

Description

msgstr = lasterr returns the last error message generated by the MATLAB® software.

[msgstr, msgid] = lasterr returns the last error in msgstr and its message identifier in msgid. If the error was not defined with an identifier, lasterr returns an empty string for msgid. See Message Identifiers in the MATLAB Programming Fundamentals documentation for more information on the msgid argument and how to use it.

lasterr('new_msgstr') sets the last error message to a new string, new_msgstr, so that subsequent invocations of lasterr return the new error message string. You can also set the last error to an empty string with lasterr('').

lasterr('new_msgstr', 'new_msgid') sets the last error message and its identifier to new strings new_msgstr and new_msgid, respectively. Subsequent invocations of lasterr return the new error message and message identifier.

[msgstr, msgid] = lasterr('new_msgstr', 'new_msgid') returns the last error message and its identifier, also changing these values so that subsequent invocations of lasterr return the message and identifier strings specified by new_msgstr and new_msgid respectively.

Examples

Example 1

Here is a function that examines the lasterr string and displays its own message based on the error that last occurred. This example deals with two cases, each of which is an error that can result from a matrix multiply:

function matrix_multiply(A, B)
try
   A * B
catch
   errmsg = lasterr;
   if(strfind(errmsg, 'Inner matrix dimensions'))
      disp('** Wrong dimensions for matrix multiply')
   else
      if(strfind(errmsg, 'not defined for variables of class'))
         disp('** Both arguments must be double matrices')
      end
   end
end

If you call this function with matrices that are incompatible for matrix multiplication (e.g., the column dimension of A is not equal to the row dimension of B), MATLAB catches the error and uses lasterr to determine its source:

A = [1  2  3; 6  7  2; 0  -1  5];
B = [9  5  6; 0  4  9];

matrix_multiply(A, B)
** Wrong dimensions for matrix multiply

Example 2

Specify a message identifier and error message string with error:

error('MyToolbox:angleTooLarge', ... 
      'The angle specified must be less than 90 degrees.');

In your error handling code, use lasterr to determine the message identifier and error message string for the failing operation:

[errmsg, msgid] = lasterr
errmsg =
   The angle specified must be less than 90 degrees.
msgid =
   MyToolbox:angleTooLarge
Was this topic helpful?