Panic in Wolfram Language

(* A "Throw" typically means something went unexpectedly wrong. 
   Mostly we use it to fail fast on errors that shouldn't occur 
   during normal operation, or that we aren't prepared to handle gracefully. *)

(* We'll use Throw throughout this site to check for unexpected errors. 
   This is the only program on the site designed to throw an exception. *)

Throw["a problem"]

(* A common use of Throw is to abort if a function returns an error value 
   that we don't know how to (or want to) handle. Here's an example of 
   throwing an exception if we get an unexpected error when creating a new file. *)

CreateFile["/tmp/file"] // Catch[#, _]&

If[FailureQ[%],
  Throw[%]
]

Running this program will cause it to throw an exception, print an error message, and exit with a non-zero status.

When the first Throw in the main block fires, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment the first Throw out.

$ wolframscript -code "(* code from above *)"
Throw::throw: Uncaught exception: a problem

Note that unlike some languages which use exceptions for handling of many errors, in Wolfram Language it is idiomatic to use failure objects (Failure[...]) for indicating and handling errors wherever possible. The Throw mechanism is typically reserved for more severe or unexpected error conditions.

In Wolfram Language, Throw and Catch are used for non-local control flow, which can be used to implement exception-like behavior. The Catch function can be used to catch a Throw, allowing for more structured error handling:

result = Catch[
  (* Your code here *)
  Throw["An error occurred"]
  ,
  _String
]

If[StringQ[result],
  Print["Caught error: ", result]
]

This structure allows for more controlled error handling, similar to try-catch blocks in other languages.