# Abort but keep what was already calculated

This is a very general question I have about aborting a running computation but keeping what was already generated.

Let's say that I perform a numerical optimization over a list of parameters. Mathematica can take quite some time to go over the whole list of parameters. Let's say I want to abort for some reason.

Is there a way to abort but keep what was already calculated?

• If "list of parameters" is a list of numbers, then something like Do[res[p] = NMinimize[...], {p, parameterList}] would save the results in res. Instead of making definitions, you could also add each result to a list or association. – Michael E2 Feb 24 '18 at 22:57
• That sounds like a good plan. It reminds me append in other "languages". I will give it a try. Thank you very much, @MichaelE2! – Laura K Feb 25 '18 at 14:18

You may use CheckAbort for that: If you evaluate the following and presss Ctrl+. then CheckAbort will evaluate the second argument; in this case, it will return the current value of i.

Module[{i = 0},
CheckAbort[
While[True,
i++
],
i
]
]

• Thank you, @HenrikShumacher. – Laura K Feb 25 '18 at 14:19
• You're very welcome. Note however that Michaek E2'a suggestion might be even better. For very long computations, it may be also worthwhile to write to file in order to be bulletproof against kernel crashes. – Henrik Schumacher Feb 25 '18 at 14:24
• I never thought about that. I am going to test both suggestions. Thank you very much, everyone! – Laura K Feb 26 '18 at 0:54