Finally Clause in Try-Catch

조회 수: 119 (최근 30일)
Mohammad Abouali
Mohammad Abouali 2016년 8월 18일
댓글: deepak panday 2020년 9월 2일
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?
  댓글 수: 1
deepak panday
deepak panday 2020년 9월 2일
isError=true
try
..
...
isError = false
throw(Me)
catch
%% this portion is executed even if error is not in the code segment
if isError
.%% write code here that need to go in error handling
end
%% write code here that need to go in finally portion
end

댓글을 달려면 로그인하십시오.

채택된 답변

Walter Roberson
Walter Roberson 2016년 8월 18일
ME = [];
try
%do some stuff
catch ME
end
%close the open resources
if ~isempty(ME)
rethrow(ME);
end
  댓글 수: 1
Mohammad Abouali
Mohammad Abouali 2016년 8월 18일
편집: Mohammad Abouali 2016년 8월 18일
I like this one. Thanks

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Guillaume
Guillaume 2016년 8월 18일
Yes, there's no finally in matlab.
It remains to be seen if raising exceptions have an impact or not on execution speed. It's not something I've tested.
It certainly seems a bit subversive to use exceptions to trigger normal completion. Probably a better way is to use onCleanup which is even more bulletproof than a finally (if the try ... finally is the whole scope of the function) since it gets triggered even on an abort (CTRL+C):
function myfunc
%Opening resources
fid = fopen('somefile');
cleanfid = onCleanup(@() fclose(fid)); %called on completion of function, whether normally, by exception or abort
%do stuff with resource
end
  댓글 수: 5
Jan Siegmund
Jan Siegmund 2020년 3월 10일
ah, got it. but the above mentioned post by guillaume wont trigger on ctrl+c, right?
So the right approach would be
function myfunc
%Opening resources
fid = fopen('bench.dat', 'rt');
cleanfid = onCleanup(@() fclose(fid)); %called on completion of function, whether normally, by exception or abort
%do stuff with resource
end
, wouldn't it?
Where it would catch on issues and ctrl+c at the
%do stuff with resource
part.
Steven Lord
Steven Lord 2020년 3월 10일
If you pressed Ctrl-C while you were doing stuff with the resource in Guillaume's example, the myfunc function would exit. As long as you don't return the onCleanup object from myfunc, it will be destroyed (and the cleanup function executed) as the myfunc function exits.
Ideally you should prefer creating the onCleanup object before making the change you want to clean up (if possible, which it is in the warning suppression case and is not in the file closing case) or as soon afterwards as you can. Anything you ran between the fopen call and the onCleanup call, if it failed, would leave the bench.dat file open.
About the only way you may be able to get a function to terminate without triggering the onCleanup objects in its workspace is to forcibly kill MATLAB (including having MATLAB crash.) If MATLAB Goes Away the operating system should handle reclaiming memory, but it's not going to allow MATLAB to try executing the onCleanup object's destructor.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by