Wolfram Research

FailOnMessage

Contributed by: Richard Hennigan (Wolfram Research)

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

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

Use the function:

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

More Examples

Scope

Retrieve the ResourceFunction:

In[2]:=
ResourceFunction["FailOnMessage"]
Out[2]=

Retrieve the ResourceObject:

In[3]:=
ResourceObject["FailOnMessage"]
Out[3]=

Give a different failure expression:

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

Ignore some messages:

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

Fail on some messages even if is quieted:

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

Applications

Some evaluations can trigger a large number of messages:

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

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

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

Use FailOnMessage to stop immediately upon encountering a message:

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

Possible Issues

When nested, the outermost FailOnMessage takes precedence:

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

Resource History

See Also