| Contents | Index |
baseExcep =
addCause(baseExcep, causeExcep)
baseExcep = addCause(baseExcep, causeExcep) adds information to existing exception baseExcep to help determine its cause. The added information is in the form of a second exception causeExcep. Both baseExcep and causeExcep are objects of the MException class. The baseExcep and causeExcep inputs are scalar objects of the mException class.
The exception has a property called cause in which you can store a series of additional exceptions, each saving information on what caused the initial error. (See the figure in the documentation for The MException Class.) When your program calls addCause, MATLAB appends a new exception cause to this field in the base exception exception. When your error handling code catches the error in a try-catch statement, execution of the catch part of this statement makes the base exception, along with all of the appended cause records, available to help diagnose the error.
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 using addCause:
function data = read_it(filename);
try
% 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? ', ...
filename);
reply = input(msg, 's')
if reply(1) == 'y'
newFolder = input('Enter folder name: ', 's');
else
throw(exception1);
end
oldpath = addpath(newFolder);
try
fid = fopen(filename, 'r');
data = fread(fid);
catch exception2
exception3 = addCause(exception2, exception1)
path(oldpath);
throw(exception3);
end
path(oldpath);
end
end
fclose(fid);try
d = read_it('anytextfile.txt');
catch exception
end
exception
exception =
MException object with properties:
identifier: 'MATLAB:FileIO:InvalidFid'
message: 'Invalid file identifier. Use fopen
to generate a valid file identifier.'
stack: [1x1 struct]
cause: {[1x1 MException]}
Cannot open file anytextfile.txt. Try another location?y
Enter folder name: xxxxxxx
Warning: Name is nonexistent or not a directory: xxxxxxx.
> In path at 110
In addpath at 89assert | catch | error | getReport(MException) | last(MException) | MException | rethrow(MException) | throw(MException) | throwAsCaller(MException) | try
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |