MATLAB: Finally Clause in Try-Catch

exception handlingMATLAB

Just making sure
MATLAB Try/Catch does not have the "finally" block? Correct?
I am simulating the behavior using something like this:
% Opening resources

try
% Doing stuff with the resources

% This is at the end of the try block so if the code reaches here
% this means that everything went well with no problem.
throw(MException('TryCatchFinally:noWorries', ...
['This exception can be ignored.' ...
'This is to just flag that the try block finished' ...
'without any error and can be used to simulate ' ...
'finally behavior'], ...
0));
catch ME
% Closing all the opened resources
% rethrowing error if it is anything other than 'TryCatchFinally:noWorries'
if (~strcmp(ME.identifier,'TryCatchFinally:noWorries') )
rethrow(ME);
end
end
However raising an exception could affect performance in cases where your code is called several times. The alternative to above code is the following but this second one requires to have the code that closes the resources twice (it's OK though if all I need to do is fclose(fid)):
% Opening resources
try
% Doing stuff with the resources
catch ME
% Closing all the opened resources;
% This is called only if any exception is raised in the try block.
rethrow(ME);
end
% Closing all the opened resources.
What other method do you guys suggest?

Best Answer

ME = [];
try
%do some stuff
catch ME
end
%close the open resources
if ~isempty(ME)
rethrow(ME);
end