poster
2019-12-10, 16:49
由于在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函数很难看并且容易出错。
有更好的方法吗?
回答:
我建议检查出ONCLEANUP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/oncleanup.html)对象。它们使您可以在函数退出时自动运行代码(更具体地说,当从内存中清除ONCLEANUP对象时)。 洛伦来自MathWorks (https://stackoverflow.com/users/113700/loren)讨论这个在她的一个博客文章在这里 (http://blogs.mathworks.com/loren/2008/03/10/keeping-things-tidy/) 。如果将上面的代码放在一个函数中,它可能看起来像这样:
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的调用引发异常,在从函数load_line返回时,仍将从内存中清除ONCLEANUP对象,从而确保关闭文件。
更多&回答... (https://stackoverflow.com/questions/1098149)
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函数很难看并且容易出错。
有更好的方法吗?
回答:
我建议检查出ONCLEANUP (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/oncleanup.html)对象。它们使您可以在函数退出时自动运行代码(更具体地说,当从内存中清除ONCLEANUP对象时)。 洛伦来自MathWorks (https://stackoverflow.com/users/113700/loren)讨论这个在她的一个博客文章在这里 (http://blogs.mathworks.com/loren/2008/03/10/keeping-things-tidy/) 。如果将上面的代码放在一个函数中,它可能看起来像这样:
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的调用引发异常,在从函数load_line返回时,仍将从内存中清除ONCLEANUP对象,从而确保关闭文件。
更多&回答... (https://stackoverflow.com/questions/1098149)