Lines that would be executed even if an error occur or if the script is aborted

When running a script and an error occurs, everything stop. The lines following the line where the error occurred wont be executed. Same think if I do ctrl-c to abort the execution.
I am using fopen and a visa object. I always have to run those line at the end of the script to close the communication to be able to reopen it when rerunning the script:
fclose(vu);
delete(vu)
clear vu
Is there a way to get these lines executed even if an error occurs before these lines or if I use ctrl-c before the script gets to these lines.Like an emergency part of the code that have always to be executed at the end no matter what.
What I am doing now is write those line manually those line in the command window when my script fails.
Thanks

 Accepted Answer

Hi Camil,
You can use try..catch. For example
try
foo()
catch
fclose(vu);
delete(vu);
clear vu;
error(...);
end
HTH

More Answers (1)

No, there is no way to do what you want with a script. With newer versions of MATLAB, however, it can be done inside a function, using oncleanup().

Categories

Community Treasure Hunt

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

Start Hunting!