How do you handle resources in MATLAB in an exception safe manner? (like “try … finally”)

后端 未结 2 1706
无人及你
无人及你 2020-11-29 02:08

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
          


        
相关标签:
2条回答
  • 2020-11-29 02:25

    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.

    0 讨论(0)
  • 2020-11-29 02:37

    My preference is to create a FileHandle class with a delete method that closes the file when the object goes out of scope. Also gives you the opportunity to do other more natural file handle-y things.

    0 讨论(0)
提交回复
热议问题