MException - Construct MException object

Syntax

ME = MException(identifier, msgstring)
ME = MException(identifier, msgformat, s1, s2, ...)

Description

ME = MException(identifier, msgstring) constructs an object ME of class MException and assigns an identifier and error message msgstring to that object. This object then provides properties and methods that you can use in generating or responding to errors in your program code.

The identifer input is a message identifier string that you can specify to uniquely identify the MException. The msgstring input is a character string that informs the user about the cause of the error. The MATLAB® software displays this error message if the program aborts due to the error.

ME = MException(identifier, msgformat, s1, s2, ...) constructs an MException object where the error message is constructed by the format string msgformat and additional string or scalar numeric values s1, s2, etc. The msgformat argument differs from msgstring (used in the previous syntax) in that it may contain escape sequences, such as \t or \n, and C language conversion specifiers, such as %s and %d that are supported by the sprintf function. Additional arguments s1, s2, etc. provide the values that correspond to these conversion specifiers. See the sprintf function reference page for more information on valid conversion specifiers.

There are two ways to generate an error in your MATLAB code. Although the latter method is more work, it can provide you with a more extensible system for reporting and handling errors:

Properties

The MException object has four properties: identifier, message, stack, and cause.

PropertyDescription
identifierIdentifies the MException string.
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

MethodDescription
AddCauseAppends an MException to the cause field of another MException.
eqCompares two MException objects for equality.
getReportReturns a formatted message string based on the current exception that uses the same format as errors thrown by internal MATLAB code.
isequalCompares two MException objects for equality.
lastReturns an MException object for the most recently thrown exception.
neCompares two MException objects for inequality.
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

When MATLAB encounters an error in its internal code or in your own program code, it throws an exception. In this exception process, MATLAB

If your program code implements a try-catch mechanism to intercept the error before MATLAB aborts the program, you can obtain access to the MException object that MATLAB associates with this error instance via the catch statement and then handle the condition based on the records you can retrieve from the object.

Examples

Example 1

If your message string requires formatting specifications, like those available with the sprintf function, you can use this syntax for the MException constructor:

ME = MException(identifier, formatstring, arg1, arg2, ...)

For example,

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

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

Example 2

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 ME1.

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);
try
   fid = fopen(filename, 'r'); 
   d_in = fread(fid); 
catch ME1 
   % Get last segment of the error message identifier.
   idSegLast = regexp(ME1.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(ME1);
      end 

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

Example 3

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 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 ME1
   if strcmp(ME1.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(ME1);
      end
      addpath(newdir);
      try
         fid = fopen(filename, 'r');
         data = fread(fid);
      catch ME2
         ME3 = addCause(ME2, ME1)
         throw(ME3);
      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

throw(MException), rethrow(MException), throwAsCaller(MException), addCause(MException), getReport(MException),disp(MException), isequal(MException), eq(MException), ne(MException), last(MException), error, try, catch

  


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