Wolfram Research

Function Repository Resource:

OnFailure

Source Notebook

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

Contributed by: Taliesin Beynon

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, apply the function of the first argument:

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

Print a $Failed when True is generated:

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

Requirements

Wolfram Language 11.3 (March 2018) or above

Resource History

License Information