This is documentation for Mathematica 3, which was
based on an earlier version of the Wolfram Language.
View current documentation (Version 11.1)
 Documentation / Mathematica / The Mathematica Book / Principles of Mathematica / Evaluation of Expressions  /

2.5.13 Advanced Topic: Interrupts and Aborts

Section 1.3.12 described how you can interrupt a Mathematica computation by pressing appropriate keys on your keyboard.
In some cases, you may want to simulate such interrupts from within a Mathematica program. In general, executing Interrupt[] has the same effect as pressing interrupt keys. On a typical system, a menu of options is displayed, as discussed in Section 1.3.12.


Interrupts and aborts.

The function Abort[] has the same effect as interrupting a computation, and selecting the abort option in the interrupt menu.
You can use Abort[] to implement an "emergency stop" in a program. In almost all cases, however, you should try to use functions like Return and Throw, which lead to more controlled behavior.

  • Abort terminates the computation, so only the first Print is executed.
  • In[1]:= Print[a]; Abort[ ]; Print[b]

    a

    Out[1]=

    If you abort at any point during the evaluation of a Mathematica expression, Mathematica normally abandons the evaluation of the whole expression, and returns the value $Aborted.
    You can, however, "catch" aborts using the function CheckAbort. If an abort occurs during the evaluation of expr in CheckAbort[expr,failexpr], then CheckAbort returns failexpr, but the abort propagates no further. Functions like Dialog use CheckAbort in this way to contain the effect of aborts.

  • CheckAbort catches the abort, prints c and returns the value aborted.
  • In[2]:= CheckAbort[Print[a]; Abort[ ]; Print[b], Print[c]; aborted]

    a

    c

    Out[2]=

  • The effect of the Abort is contained by CheckAbort, so b is printed.
  • In[3]:= CheckAbort[Print[a]; Abort[ ], Print[c]; aborted]; Print[b]

    a

    c

    b

    When you construct sophisticated programs in Mathematica, you may sometimes want to guarantee that a particular section of code in a program cannot be aborted, either interactively or by calling Abort. The function AbortProtect allows you to evaluate an expression, saving up any aborts until after the evaluation of the expression is complete.

  • The Abort is saved up until AbortProtect is finished.
  • In[4]:= AbortProtect[Abort[ ]; Print[a]]; Print[b]

    a

    Out[4]=

  • The CheckAbort sees the abort, but does not propagate it further.
  • In[5]:= AbortProtect[Abort[ ]; CheckAbort[Print[a], x]]; Print[b]

    b

    Even inside AbortProtect, CheckAbort will see any aborts that occur, and will return the appropriate failexpr. Unless this failexpr itself contains Abort[], the aborts will be "absorbed" by the CheckAbort.