5
$\begingroup$

I am calling a function that I terminate using TimeConstrained[] if the function doesn't complete in some time. Since TimeConstrained[] returns $Aborted, I thought I will use CheckAbort[] to test for Abort signal and return a default value on failure. I am unable to understand the behavior of CheckAbort[]. As Abort[] and TimeContrained[] both return the special symbol $Aborted, I assumed that the behavior would be the same. I expected the variable test to have value 0 in both cases below but the behavior is confusing.

test = CheckAbort[TimeConstrained[Pause[2], 1], 0]
test = CheckAbort[Abort[], 0]

Output:

$Aborted
0
$\endgroup$
  • 2
    $\begingroup$ If the abort signal is not crucial for your application, you could also use the third argument to TimeConstrained: TimeConstrained[Pause[2], 1, 0]. $\endgroup$ – WReach Apr 3 at 4:00
  • 1
    $\begingroup$ While the underlying assumption is perfectly reasonable, this issue of TimeConstrained and CheckAbort not being on speaking terms is a long-standing one. I am optimistic that it will finally resolved in the version 12.2 time frame. For now the approach in the response by @Nasser seems like a viable workaround. $\endgroup$ – Daniel Lichtblau Apr 3 at 16:53
7
$\begingroup$

Need to throw an Abort[] when it times out to catch it.

res = CheckAbort[TimeConstrained[Pause[2], 1, Abort[]], 0]

(*0*)

or

res = CheckAbort[TimeConstrained[Pause[2], 1, Abort[]],"Oh no, timed out"]
(* Oh no, timed out *)
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.