Products & Services Solutions Academia Support User Community Company

Learn more about MATLAB   

MException - Capture error information

Syntax

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

Description

exception = MException(msgIdent, msgString, v1, v2, ...) captures information about a specific error that has occurred and stores it in error record exception. Information stored in the record includes a message identifier msgIdent and an error message string msgString. Optional arguments v1, v2, ... represent additional values you would like MATLAB to add to the error message string at run time.

Message identifier msgIdent is a character string composed of 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. msgString can include predefined escape sequences, such as \n for newline, and conversion specifiers, such as %d for a decimal number.

Inputs v1, v2, ... represent numeric values or substrings that are to replace conversion specifiers used in the msgString input. The format is the same as that used with the sprintf function. v1 replaces the first conversion specifier in msgString, v2 replaces the second, and so on. 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. The vn arguments replace the conversion specifiers at the time of execution.

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, assert, throw, rethrow, and throwAsCaller. See the documentation and figure in the section The MException Class for more information on this class.

Properties

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

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

Methods

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

MethodDescription
addCauseAppends an MException to the cause field of another MException.
getReportReturns a formatted message string based on the current exception that uses the same format as errors thrown by internal MATLAB code.
lastReturns an MException object for the most recently thrown exception.
rethrowReissues an exception that has been caught, causing the program to stop.
throwIssues an exception from the currently running M-file.
throwAsCallerIssues an exception from the currently running M-file, also omitting the current stack frame from the stack field of the MException.

Remarks

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. If msgString is an empty string, the error command has no effect.

Examples

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');

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

Example 2 — Error Recovery

This example reads the contents of an image file. The attempt to open and then read the file is done in a try block. If either the open or read fails, the program catches the resulting exception and saves the MException object in the variable exception1.

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 file name 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);
try
   fid = fopen(filename, 'r'); 
   d_in = fread(fid); 
catch exception_1 
   % Get last segment of the error message identifier.
   idSegLast = regexp(exception_1.identifier, ...
               '(?<=:)\w+$', 'match');

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

      % Yes. Try modifying the filename extension.
      switch ext
      case '.jpg'    % Change jpg to jpeg 
          filename = strrep(filename, '.jpg', '.jpeg')
      case '.jpeg'   % Change jpeg to jpg 
          filename = strrep(filename, '.jpeg', '.jpg')
      case '.tif'    % Change tif to tiff 
          filename = strrep(filename, '.tif', '.tiff')
      case '.tiff'   % Change tiff to tif 
          filename = strrep(filename, '.tiff', '.tif')
      otherwise 
         fprintf('File %s not found\n', filename);
         rethrow(exception_1);
      end 

      % Try again, with modifed filenames.
      try
         fid = fopen(filename, 'r'); 
         d_in = fread(fid);
      catch exception_2
         fprintf('Unable to access file %s\n', filename);
         exception_2 = addCause(exception_2, exception_1);
         rethrow(exception_2)
      end 
   end 
end

Example 3 — Nested try-catch

This example attempts to open a file in a directory 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);
try
   fid = fopen(filename, 'r');
   data = fread(fid);
catch exception_1
   if strcmp(exception_1.identifier, 'MATLAB:FileIO:InvalidFid')
      msg = sprintf('\n%s%s%s', 'Cannot open file ', ...
         filename, '. Try another location?  ');
      reply = input(msg, 's')
      if reply(1) == 'y'
          newdir = input('Enter directory name:  ', 's');
      else
          throw(exception_1);
      end
      addpath(newdir);
      try
         fid = fopen(filename, 'r');
         data = fread(fid);
      catch exception_2
         exception_3 = addCause(exception_2, exception_1)
         throw(exception_3);
      end
      rmpath(newdir);
   end
end
fclose(fid);

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.

See Also

The MException Class, try, catch, error, assert, throw(MException), rethrow(MException), throwAsCaller(MException), addCause(MException), getReport(MException),last(MException), dbstack

  


Recommended Products

Includes the most popular MATLAB recorded presentations with Q&A sessions led by MATLAB experts.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS