Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
689 views
in Technique[技术] by (71.8m points)

file io - How do you handle resources in MATLAB in an exception safe manner? (like "try ... finally")

Since there is no finally clause to the try-catch block in MATLAB, I find myself writing lots of code like the following:

fid = fopen(filename);
if fid==-1
    error('Couldn''t open file');
end
try
   line = getl(fid);
catch ME
   fclose(fid);
   rethrow ME;
end
fclose(fid);

I find having the fclose function in two places ugly and error prone.

Is there a better way for doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I would suggest checking out ONCLEANUP objects. They allow you to automatically run code on exit from a function (more specifically, when the ONCLEANUP object is cleared from memory). Loren from The MathWorks discusses this in one of her blog posts here. If you place your above code in a function, it might look something like this:

function data = load_line(filename)
  data = [];
  fid = fopen(filename);
  if fid == -1
      error('Couldn''t open file');
  end
  c = onCleanup(@()fclose(fid));
  data = getl(fid);
end

Even if the call to GETL throws an exception, the ONCLEANUP object will still be cleared from memory on return from the function load_line, thus ensuring the file gets closed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...