Throw

Throw[value]
stops evaluation and returns value as the value of the nearest enclosing Catch.

Throw[value, tag]
is caught only by Catch[expr, form] where form is a pattern that matches tag.

DetailsDetails

  • You can use Throw and Catch to exit functions such as Nest, Fold, FixedPoint, and Scan.
  • tag can be any expression.
  • tag in Throw[value, tag] is re-evaluated every time it is compared to form in Catch[expr, form].
  • An error is generated and an unevaluated Throw is returned if there is no appropriate enclosing Catch to catch the Throw.

ExamplesExamplesopen allclose all

Basic Examples (3)Basic Examples (3)

Exit to the enclosing Catch as soon as Throw is evaluated:

In[1]:=
Click for copyable input
Out[1]=

Define a function that can "throw an exception":

In[1]:=
Click for copyable input

The result of Catch is just what is thrown by Throw:

In[2]:=
Click for copyable input
Out[2]=
In[3]:=
Click for copyable input
Out[3]=

Use Throw to exit a loop when a criterion is satisfied:

In[1]:=
Click for copyable input
Out[1]=
New in 1 | Last modified in 3
New to Mathematica? Find your learning path »
Have a question? Ask support »