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 ResourceFunction["OnFailure"].

Examples

Basic Examples (3) 

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

Version History

  • 1.0.0 – 01 February 2019

License Information