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 tag matches form.

Throw[value,tag,f]

returns f[value,tag] as the top-level value if no appropriate Catch is found.

Details

  • 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 reevaluated 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.

Examples

open allclose all

Basic Examples  (3)

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

Define a function that can "throw an exception":

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

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

Scope  (4)

Throw works inside essentially any function:

Use Throw to throw any type of expression:

Throw is caught by the nearest enclosing Catch:

As soon as the first Throw is evaluated, it exits to the enclosing Catch:

Generalizations & Extensions  (3)

Catch Throw with tag u:

The inner Catch catches Throw:

The outer Catch catches Throw:

Keep the tag local:

Applications  (3)

Find the next prime after 1010:

Find the first power of 17 equal to 1 mod 19:

Stop if an iteration gets too large:

Properties & Relations  (1)

Use Check to throw an exception if a message is generated:

Possible Issues  (2)

Throw requires Catch:

Using Throw can affect the structure of what is returned by a function:

Wolfram Research (1988), Throw, Wolfram Language function, https://reference.wolfram.com/language/ref/Throw.html (updated 2020).

Text

Wolfram Research (1988), Throw, Wolfram Language function, https://reference.wolfram.com/language/ref/Throw.html (updated 2020).

CMS

Wolfram Language. 1988. "Throw." Wolfram Language & System Documentation Center. Wolfram Research. Last Modified 2020. https://reference.wolfram.com/language/ref/Throw.html.

APA

Wolfram Language. (1988). Throw. Wolfram Language & System Documentation Center. Retrieved from https://reference.wolfram.com/language/ref/Throw.html

BibTeX

@misc{reference.wolfram_2024_throw, author="Wolfram Research", title="{Throw}", year="2020", howpublished="\url{https://reference.wolfram.com/language/ref/Throw.html}", note=[Accessed: 23-November-2024 ]}

BibLaTeX

@online{reference.wolfram_2024_throw, organization={Wolfram Research}, title={Throw}, year={2020}, url={https://reference.wolfram.com/language/ref/Throw.html}, note=[Accessed: 23-November-2024 ]}