Wolfram Research

OnFailure

Contributed by: Taliesin Beynon

Source Notebook

Apply a function on an expression when FailureQ gives True on it, otherwise return the expression

ResourceFunction["OnFailure"][f,expr]

gives f[expr] if FailureQ[expr] is True, otherwise gives expr.

ResourceFunction["OnFailure"][f]

is an operator form of OnFailure.

Examples

Basic Examples

OnFailure returns the result of the second argument if it is not $Failed:

In[1]:=
ResourceFunction["OnFailure"][h, 3]
Out[1]=
In[2]:=
ResourceFunction["OnFailure"][Print, AbortProtect[Abort[]]]
Out[2]=

Otherwise applies the function of the first argument:

In[3]:=
ResourceFunction["OnFailure"][f, $Failed]
Out[3]=

Print a $Failed when is generated:

In[4]:=
ResourceFunction["OnFailure"][Print, OpenRead["non-existing.file"]]

Resource History