Close diary file on Error
21 次查看(过去 30 天)
显示 更早的评论
Hi, I am using the diary function to log my application output. Something like
diary(path_to_logfile)
% all my code with output to the console, matrices written to desk, etc
diary off
When the code fails, the diary is not closed. One option would be to wrap all the code on a try-catch statement and close it on the catch.
Is there another way to avoid the diary being "open" when the app fails?
0 个评论
采纳的回答
Jan
2012-7-20
TRY-CATCH is really the best solution:
diary(path_to_logfile)
try
% all my code with output to the console, matrices written to desk, etc
catch ME
fprintf(1, 'ERROR:\n%s\n', ME.message);
end
diary off
This is clean an efficient, and you could insert other code for cleanup also, e.g. fclose('all').
更多回答(2 个)
Andrew Janke
2020-1-31
The onCleanup function is what you want in modern Matlab. No try/catch to ugly up your code, and it's robust even against a dbquit.
function my_function
diary(path_to_logfile)
RAII.diary = onCleanup(@() diary('off'))
% ... now do whatever, and don't worry about closing the diary; it'll
% be automatically closed whenever this function returns for any reason...
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Scope Variables and Generate Names 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!