Function Repository Resource:

FailOnMessage

Source Notebook

Stop an evaluation when a message is encountered and return a given failure expression

Contributed by: Richard Hennigan (Wolfram Research)

ResourceFunction["FailOnMessage"][eval]

stops evaluation of eval if a message occurs and returns $Failed.

ResourceFunction["FailOnMessage"][eval,default]

stops evaluation of eval if a message occurs and returns default.

ResourceFunction["FailOnMessage"][eval,default,quiet]

stops evaluation of eval if a message occurs and returns default while ignoring messages in quiet.

ResourceFunction["FailOnMessage"][eval,default,quiet,listen]

stops evaluation of eval if any message in listen occurs,even if quieted.

Examples

Basic Examples (2) 

Return $Failed if a message occurs:

In[1]:=
ResourceFunction["FailOnMessage"][1/0]
Out[1]=

Give a different failure expression:

In[2]:=
ResourceFunction["FailOnMessage"][1/0, Nothing]
Out[2]=

Scope (2) 

Ignore some messages:

In[3]:=
ResourceFunction["FailOnMessage"][
 Table[First[1], 5], $Failed, {First::normal}]
Out[3]=

Fail on some messages even if quieted:

In[4]:=
ResourceFunction["FailOnMessage"][
 Quiet[Table[First[1], 5], {First::normal}], $Failed, None, {First::normal}]
Out[4]=

Applications (3) 

Some evaluations can trigger a large number of messages:

In[5]:=
f[n_] := Module[{x := Table[1/0 + 0^0, n]}, {x, x}];
f[3]
Out[5]=

Check can be used to return a different expression if a message occurs, but the full evaluation still takes place:

In[6]:=
Check[f[3], $Failed]
Out[6]=

Use FailOnMessage to stop immediately upon encountering a message:

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

Possible Issues (1) 

When nested, the outermost FailOnMessage takes precedence:

In[8]:=
outer[ResourceFunction["FailOnMessage"][
  Echo[inner[
    ResourceFunction["FailOnMessage"][1/0, $inner]]], $outer]]
Out[8]=

Requirements

Wolfram Language 11.3 (March 2018) or above

Version History

  • 1.0.0 – 15 August 2018

Related Resources

License Information