1

I'm sure this has been asked before but I just cant find it.

What I want to do is have some code run when I abort(CTRL+C) a script while it's running, for example, if I open a file I'd like the close command to run even if I abort or there's an error.

Something like try\finally in other languages, only there's no error on abort so try\catch will not work here.

Thanks.

pseudoDust
  • 1,336
  • 1
  • 10
  • 18
  • See the Java implementation. [Matlab: implementing what CTRL+C does, but in the code][1]. [1]: http://stackoverflow.com/questions/10033078/matlab-implementing-what-ctrlc-does-but-in-the-code – m_power Mar 04 '14 at 18:36

2 Answers2

3

Take a look at onCleanup, which is intended for exactly this purpose.

onCleanup creates an object that, when it goes out of scope (and therefore gets deleted), executes some code. So, for example,

c1 = onCleanup(@() disp('goodbye'))

creates an object c1. When c1 goes out of scope, it is deleted, and goodbye is displayed. Similarly

c2 = onCleanup(@() fclose(fid))

creates an object that, when deleted, closes the file with ID fid.

You'll need to make a change to your coding style to take advantage of onCleanup - specifically, you'll need to implement things as functions rather than scripts. Scripts use the base workspace, so when the finish, any cleanup objects you've created remain in the base workspace without going out of scope and being deleted, so their code never executes.

By contrast, functions have their own workspace, which is cleared when they finish, automatically deleting any cleanup objects. Importantly for your question, this workspace is cleared not only when the function finishes normally, but also if it finishes with an error, and even if it finishes with CtrlC.

It's usually simple to modify a script to a function: if the script is called mytest.m, just put function mytest at the top of the script. There are situations where this won't work (e.g. if your script depends on other variables being available in the base workspace), but those are situations that it's not a good idea to be in anyway.

As an example, run the following program:

function mytest

c = onCleanup(@() disp('goodbye'));

for i = 1:1000000
    disp(i)
end

During execution, hit CtrlC. You should see that goodbye is displayed after the last number.

Sam Roberts
  • 23,951
  • 1
  • 40
  • 64
0

You can't customize the CTRL-C shortcut.

See Actions for Which You Cannot Customize Keyboard Shortcuts in the matlab doc.

marsei
  • 7,691
  • 3
  • 32
  • 41