| Contents | Index |
try statements catch exception statements end
try and catch blocks allow you to override the default error behavior for a set of program statements. If any statement in a try block generates an error, program control goes immediately to the catch block, which contains your error handling statements.
exception is an optional MException object input to the catch block that allows you to identify the error.
Both try and catch blocks can contain nested try/catch statements.
Provide more information about a dimension mismatch error:
A = rand(3);
B = ones(5);
try
C = [A; B];
catch err
% Give more information for mismatch.
if (strcmp(err.identifier,'MATLAB:catenate:dimensionMismatch'))
msg = sprintf('%s', ...
'Dimension mismatch occured: First argument has ', ...
num2str(size(A,2)), ' columns while second has ', ...
num2str(size(B,2)), ' columns.');
error('MATLAB:myCode:dimensions', msg);
% Display any other errors as usual.
else
rethrow(err);
end
end % end try/catchCatch an error when reading an image file, and try adjusting the file extension to resolve the error (.jpg and .jpeg are similar, as are .tif and .tiff):
function imageData = readImage(filename)
try
imageData = imread(filename);
catch exception
% Is the error because MATLAB could not find the file?
if ~exist(filename, 'file')
% Check for common typos in the extension.
[~, ~, extension] = fileparts(filename);
switch extension
case '.jpg'
altFilename = strrep(filename, '.jpg', '.jpeg');
case '.jpeg'
altFilename = strrep(filename, '.jpeg', '.jpg');
case '.tif'
altFilename = strrep(filename, '.tif', '.tiff');
case '.tiff'
altFilename = strrep(filename, '.tiff', '.tif');
otherwise
rethrow(exception);
end
% Try again, with modifed filename.
try
imageData = imread(altFilename);
catch exception2
% Rethrow original error.
rethrow(exception)
end
else
rethrow(exception)
end
endassert | error | MException

Explore how to use MATLAB to make advancements in engineering and science.
| © 1984-2012- The MathWorks, Inc. - Site Help - Patents - Trademarks - Privacy Policy - Preventing Piracy - RSS |