% Check the number of input arguments.
if nargin < 1
me = MException('MATLAB:notEnoughInputs','Not enough input arguments.');
aac = matlab.lang.correction.AppendArgumentsCorrection('"image.png"');
me = me.addCorrection(aac);
throw(me);
end
% Attempt to read file and catch an exception if it arises.
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 modified 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
This example illustrates some of the actions that you can take in response to an
exception.
- Compare the identifier field of the MException object to possible causes of the
error. In this case, the function checks whether the identifier ends in 'InvalidFid',
indicating a file could not be found. - Use a nested try/catch statement to retry the operation with improved input. In this
case, the function retries the open and read operations using a known variation of the
filename extension.
26 Error Handling