# Implementing custom return functions for easier error handling

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

error["Message"]


Print["Message"];
Return[<|"Success" -> False|>]


and

success[return]


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?

• Have a look at Returning a value from a Module. – Carl Woll Jul 11 '17 at 15:36
• @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. – 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_] := (
Print[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

f[1]
1


while negative number yields an error

f[-1]
Invalid number
<|"Success" -> False|>


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