如何以异常安全的方式处理MATLAB中的资源? (如“最后尝试”) [英] How do you handle resources in MATLAB in an exception safe manner? (like "try ... finally")

查看:129
本文介绍了如何以异常安全的方式处理MATLAB中的资源? (如“最后尝试”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于MATLAB中没有finally-try块,所以我发现自己编写了如下代码:

  fid = fopen(filename); 
如果fid == - 1
错误('不能打开文件');
end
try
line = getl(fid);
catch ME
fclose(fid);
rethrow ME;
end
fclose(fid);

我发现fclose功能在两个地方丑陋,容易出错。



有没有更好的方法?

解决方案

建议您查看 ONCLEANUP 对象。它们允许您在退出函数时自动运行代码(更具体地说,当内存中清除ONCLEANUP对象时)。 MathWorks的Loren 在她的一篇博文中讨论了这一点:这里。如果将上面的代码放在一个函数中,可能看起来像这样:

  function data = load_line(filename)
data = [];
fid = fopen(filename);
如果fid == -1
错误('不能打开文件');
end
c = onCleanup(@()fclose(fid));
data = getl(fid);
end

即使对GETL的调用抛出异常,ONCLEANUP对象仍然是从功能 load_line 返回时从内存中清除,从而确保文件关闭。


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?

解决方案

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.

这篇关于如何以异常安全的方式处理MATLAB中的资源? (如“最后尝试”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆