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?

 Akzeptierte Antwort

Jan
Jan am 20 Jul. 2012

1 Stimme

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 Kommentar

gire
gire am 20 Jul. 2012
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 :)

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (2)

Walter Roberson
Walter Roberson am 20 Jul. 2012

3 Stimmen

onCleanup() might be appropriate for you.
Andrew Janke
Andrew Janke am 31 Jan. 2020

2 Stimmen

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

2 Kommentare

Florian Rössing
Florian Rössing am 6 Mai 2022
Super usefull, thank you
Tria Technologies
Tria Technologies am 29 Jan. 2025
Upvoting the use of onCleanup I recently discovered this and it has added better predictability to functions. Of course, classes have built in delete() methods for doing the same.

Melden Sie sich an, um zu kommentieren.

Kategorien

Mehr zu Scope Variables and Generate Names finden Sie in Hilfe-Center und File Exchange

Gefragt:

am 20 Jul. 2012

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by