| MATLAB® | ![]() |
ME = MException(msgID, errmsg, v1,
v2, ...)
ME = MException(msgID, errmsg, v1, v2, ...) constructs an object ME of class MException and assigns to that object a message identifier msgID and error message string errmsg. This object then provides properties and methods that you can use in generating or responding to errors in your program code.
The msgID argument is a unique message identifier string that MATLAB attaches to the error message when it throws the error. A message identifier has the format component:mnemonic. Its purpose is to better identify the source of the error (see Message Identifiers in the MATLAB Programming Fundamentals documentation for more information).
The errmsg argument 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 errmsg string can include predefined escape sequences, such as \n for newline, and conversion specifiers, such as %d for a decimal number.
The v1, v2, ... arguments represent values or substrings that are to replace conversion specifiers used in the errmsg string. The format is the same as that used with the sprintf function. For example, if errmsg 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.
Valid escape sequences for the errmsg string are \b, \f, \n, \r, \t, and \x or \ when followed by a valid hexadecimal or octal number, respectively. Following a backslash in the errmsg 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 errMsg is an empty string, the error command has no effect.
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:
Call the MATLAB error function.
Construct an MException object, store identifying information in the object, and use the throw or throwAsCaller methods of that object to generate the error.
The MException object has four properties: identifier, message, stack, and cause.
| Property | Description |
|---|---|
| identifier | Identifies the MException string. |
| message | Formatted error message that is displayed. |
| stack | Structure containing stack trace information such as M-file function name and line number where the MException was thrown. |
| cause | Cell array of MException that caused this exception to be created. |
| Method | Description |
|---|---|
| addCause | Appends an MException to the cause field of another MException. |
| eq | Compares two MException objects for equality. |
| getReport | Returns a formatted message string based on the current exception that uses the same format as errors thrown by internal MATLAB code. |
| isequal | Compares two MException objects for equality. |
| last | Returns an MException object for the most recently thrown exception. |
| ne | Compares two MException objects for inequality. |
| rethrow | Reissues an exception that has been caught, causing the program to stop. |
| throw | Issues an exception from the currently running M-file. |
| throwAsCaller | Issues an exception from the currently running M-file, also omitting the current stack frame from the stack field of the MException. |
When MATLAB encounters an error in its internal code or in your own program code, it throws an exception. In this exception process, MATLAB:
Interrupts the program at the point of the error.
Constructs an object of the MException class.
Records information about the error in that object.
Displays this information at the user's terminal.
Aborts the program.
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.
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.
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 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 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
endThis 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 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.
throw(MException), rethrow(MException), throwAsCaller(MException), addCause(MException), getReport(MException),disp(MException), isequal(MException), eq(MException), ne(MException), last(MException), error, try, catch
![]() | mex.getCompilerConfigurations | mexext | ![]() |

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 |