Documentation Center

  • Trials
  • Product Updates


Capture error information


exception = MException(msgIdent, msgString, v1, v2, ..., vN)


exception = MException(msgIdent, msgString, v1, v2, ..., vN) captures information about a specific error and stores it in MException object, exception. Information stored in the object includes a message identifier msgIdent and an error message string msgString. Optional arguments v1, v2, ... represent text or numeric values that replace conversion specifiers in msgString at run time.

Message identifier msgIdent is a character string composed of at least two substrings, the component and the mnemonic, separated by a colon (e.g., component:mnemonic). The purpose of the identifier is to better identify the source of the error. See the documentation on Message Identifiers for more information.

Message string msgString is a character string that informs the user about the cause of the error and can also suggest how to correct the faulty condition. The msgString string can include escape sequences such as \t or \n, as well as any of the format specifiers supported by the sprintf function (such as %s or %d). Additional arguments v1, v2, ..., vN provide values that correspond to and replace the conversion specifiers.

For example, if msgString is "Error on line %d, command %s", then v1 is the line number at which the error was detected, and v2 is the command that failed. See Formatting Strings in the MATLAB® Programming Fundamentals documentation for more detailed information on using string formatting commands.

The exception output is an object of the MException class. MException is the constructor for this class. In addition to calling the constructor directly, you can also create an object of MException with any of the following functions: error and assert. See the documentation and figure in the section The MException Class for more information on this class.


The MException object has four properties: identifier, message, stack, and cause. Click any of the links below to find out more about MException properties:

identifierIdentifies the error.
messageFormatted error message that is displayed.
stackStructure containing stack trace information such as file name, function name, and line number where the MException was thrown.
causeCell array of MException that caused this exception to be created.


The MException class has the following methods. Click any of the links below to find out more about MException methods:

addCauseAppends an MException to the cause field of another MException.
eqTests scalar MException objects for equality.
getReportReturns a formatted message string that uses the same format as errors thrown by internal MATLAB code.
isequalTests scalar MException objects for equality.
lastReturns an MException object for the most recently thrown exception.
neTests scalar MException objects for inequality.
rethrowReissues an exception that has been caught, causing the program to stop.
throwIssues an exception from the currently running function.
throwAsCallerIssues an exception from the currently running function, also omitting the current stack frame from the stack field of the MException.


Example 1 — Formatted Messages

If your message string requires formatting specifications like those used with the sprintf function, you can use this syntax to compose the error message string:

exception = MException(msgIdent, msgString, v1, v2, ...)

For example,

exception = MException('AcctError:Incomplete', ...
      'Field ''%s.%s'' is not defined.', ...
      'Accounts', 'ClientName');

ans =
    Field 'Accounts.ClientName' is not defined.

Example 2

The catch block in this example checks to see if the specified file could not be found. If this is the case, the program allows for the possibility that a common variation of the filename extension (e.g., jpeg instead of jpg) was used by retrying the operation with a modified extension. This is done using a try/catch statement that is nested within the original try/catch.

function d_in = read_image(filename)
[path name ext] = fileparts(filename);
   fid = fopen(filename, 'r'); 
   d_in = fread(fid); 
catch exception

   % Did the read fail because the file could not be found?
   if ~exist(filename, 'file')

      % Yes. Try modifying the filename extension.
      switch ext
      case '.jpg'    % Change jpg to jpeg 
          altFilename = strrep(filename, '.jpg', '.jpeg')
      case '.jpeg'   % Change jpeg to jpg 
          altFilename = strrep(filename, '.jpeg', '.jpg')
      case '.tif'    % Change tif to tiff 
          altFilename = strrep(filename, '.tif', '.tiff')
      case '.tiff'   % Change tiff to tif 
          altFilename = strrep(filename, '.tiff', '.tif')

      % Try again, with modifed filename.
         fid = fopen(altFilename, 'r'); 
         d_in = fread(fid);

Example 3 — Nested try/catch

This example attempts to open a file in a folder that is not on the MATLAB path. It uses a nested try-catch block to give the user the opportunity to extend the path. If the file still cannot be found, the program issues an exception with the first error appended to the second:

function data = read_it(filename);
   % Attempt to open and read from a file.
   fid = fopen(filename, 'r');
   data = fread(fid);
catch exception1
   % If the error was caused by an invalid file ID, try 
   % reading from another location.
   if strcmp(exception1.identifier, 'MATLAB:FileIO:InvalidFid')
      msg = sprintf( ...
         '\nCannot open file %s. Try another location?  ', ...
      reply = input(msg, 's')
      if reply(1) == 'y'
          newFolder = input('Enter folder name:  ', 's');
      oldpath = addpath(newFolder);
         fid = fopen(filename, 'r');
         data = fread(fid);
      catch exception2
         exception3 = addCause(exception2, exception1)

If you run this function in a try-catch block at the command line, you can look at the MException object by assigning it to a variable (e) with the catch command.

More About

expand all


Valid escape sequences for the msgString argument are \b, \f, \n, \r, \t, and \x or \ when followed by a valid hexadecimal or octal number, respectively. Following a backslash in the msgString with any other character causes MATLAB to issue a warning. Conversion specifiers are similar to those used in the C programming language and in the sprintf function.

All string input arguments must be enclosed in single quotation marks.

See Also

| | | | | | | | | | | |

Related Examples

Was this topic helpful?