I was writing a package that retrieved data from various sources in order to use it in computations when I realized it would be practical to have a simple method of error handling.

Ideally, I would like to be able to write


instead of

Return[<|"Success" -> False|>]



instead of

Return[<|"Success" -> True, "Return" -> return|>]

However, I am struggling as how to implement this in Mathematica. Clearly, one can't make use of SetDelayed because then Return would relate to the wrong function. Is there a way around?

  • $\begingroup$ Have a look at Returning a value from a Module. $\endgroup$ – Carl Woll Jul 11 '17 at 15:36
  • $\begingroup$ @CarlWoll Thank you. The suggested solution turned out to work. I am surprised that such a great feature doesn't get much attention in the documentation, since I specifically looked up Return function before posting. $\endgroup$ – Samuel Novák Jul 11 '17 at 15:55

The solution suggested by Carl Woll seems to work. For the reference, I will post an example.

Using the option on Module, function error can be implemented as follows:

error[message_] := (
  Return[<|"Success" -> False|>, Module]

To test the behaivour, lets assume the following function f:

f[x_] := Module[{},
  If[x > 0, x, error["Invalid number"]]

As expected, supplying non-negative number works


while negative number yields an error

Invalid number
<|"Success" -> False|>

However, note that this solutions assumes the use of Module in the enclosing function.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.