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

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

问题描述

由于 MATLAB 中的 try-catch 块没有 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);

我发现在两个地方使用 fclose 函数既丑陋又容易出错.

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

有没有更好的方法来做到这一点?

Is there a better way for doing this?

推荐答案

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

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

即使对GETL的调用抛出异常,ONCLEANUP对象仍会在从函数load_line返回时从内存中清除,从而确保文件被关闭.

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天全站免登陆