Close diary file on Error

조회 수: 17 (최근 30일)
gire
gire 2012년 7월 20일
댓글: Florian Rössing 2022년 5월 6일
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?

채택된 답변

Jan
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').
  댓글 수: 1
gire
gire 2012년 7월 20일
I was hoping for another option because I do not like having all my code wrapped by try-catch. After some research and your answer I think this is the only option. Thanks :)

댓글을 달려면 로그인하십시오.

추가 답변 (2개)

Walter Roberson
Walter Roberson 2012년 7월 20일
onCleanup() might be appropriate for you.

Andrew Janke
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
  댓글 수: 1
Florian Rössing
Florian Rössing 2022년 5월 6일
Super usefull, thank you

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile 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!

Translated by