![]() |
您如何以异常安全的方式处理MATLAB中的资源? (例如“终于尝试...”)
由于在MATLAB中的try-catch块中没有finally子句,因此我发现自己编写了许多如下代码:
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函数很难看并且容易出错。 有更好的方法吗? 回答: 我建议检查出[URL="http://www.mathworks.com/access/helpdesk/help/techdoc/ref/oncleanup.html"]ONCLEANUP[/URL]对象。它们使您可以在函数退出时自动运行代码(更具体地说,当从内存中清除ONCLEANUP对象时)。 [URL="https://stackoverflow.com/users/113700/loren"]洛伦来自MathWorks[/URL]讨论这个在她的一个博客文章[URL="http://blogs.mathworks.com/loren/2008/03/10/keeping-things-tidy/"]在这里[/URL] 。如果将上面的代码放在一个函数中,它可能看起来像这样: 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的调用引发异常,在从函数[B]load_line[/B]返回时,仍将从内存中清除ONCLEANUP对象,从而确保关闭文件。 [url=https://stackoverflow.com/questions/1098149]更多&回答...[/url] |
所有时间均为北京时间。现在的时间是 23:32。 |
Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.