Throw
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 all close allBasic Examples (3)
Exit to the enclosing Catch as soon as Throw is evaluated:
Catch[a;b;Throw[c];d;e]Define a function that can "throw an exception":
f[x_] := If[x > 10, Throw[overflow], x!]The result of Catch is just what is thrown by Throw:
Catch[f[2] + f[11]]Catch[f[2] + f[3]]Use Throw to exit a loop when a criterion is satisfied:
Catch[Do[If[i! > 10 ^ 10, Throw[i]], {i, 100}]]Scope (4)
Throw works inside essentially any function:
Catch[If[# < 0, Throw[#]]& /@ {1, 2, 0, -1, 5, 6}]Catch[{a, Throw[b], c}]Catch[a ^ 2 + b ^ 2 + c ^ 2 /. b :> Throw[bbb]]Use Throw to throw any type of expression:
Catch[If[NumericQ[#], Throw[#]]& //@ Integrate[1 / (x ^ 5 - 1), x]]Throw is caught by the nearest enclosing Catch:
Catch[{Catch[{a, Throw[b], c}], d, e}]As soon as the first Throw is evaluated, it exits to the enclosing Catch:
Catch[{Throw[a], Throw[b], Throw[c]}]Catch[Throw /@ {a, b, c}]Generalizations & Extensions (3)
Catch Throw with tag u:
Catch[Throw[a, u], u]The inner Catch catches Throw:
Catch[f[Catch[Throw[a, u], u]], v]The outer Catch catches Throw:
Catch[f[Catch[Throw[a, u], v]], u]Module[{u}, Catch[Throw[a, u], u]]Applications (3)
Find the next prime after 1010:
Catch[Do[If[PrimeQ[i], Throw[i]], {i, 10 ^ 10, 10 ^ 10 + 1000}]]Find the first power of 17 equal to 1 mod 19:
Catch[Do[If[Mod[17 ^ i, 19] == 1, Throw[i]], {i, 19}]]Stop if an iteration gets too large:
NestList[# ^ 2 + 1&, 2, 6]Catch[NestList[If[# > 1000, Throw[#], # ^ 2 + 1]&, 2, 6]]Properties & Relations (1)
Use Check to throw an exception if a message is generated:
Catch[2 + Check[1 / (1 + 1 / 0), Throw[error]]]Catch[2 + Check[1 / (1 + 1 / 2), Throw[error]]]Tech Notes
Related Guides
History
Introduced in 1988 (1.0) | Updated in 1996 (3.0) ▪ 2020 (12.2)
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_2026_throw, author="Wolfram Research", title="{Throw}", year="2020", howpublished="\url{https://reference.wolfram.com/language/ref/Throw.html}", note=[Accessed: 15-June-2026]}
BibLaTeX
@online{reference.wolfram_2026_throw, organization={Wolfram Research}, title={Throw}, year={2020}, url={https://reference.wolfram.com/language/ref/Throw.html}, note=[Accessed: 15-June-2026]}