Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Propagate a Throw upward to the outermost NestedCatch
ResourceFunction["NestedCatch"][expr] catches the first evaluation of Throw[e] and propagates it to the next enclosing NestedCatch if available. | |
ResourceFunction["NestedCatch"][expr,form,f] returns f[value,tag]. |
Exit to the enclosing NestedCatch as soon as the Throw is evaluated:
In[1]:= |
Out[1]= |
When nested, the Throw propagates upward to the outermost NestedCatch:
In[2]:= |
Out[2]= |
Compare to Catch:
In[3]:= |
Out[3]= |
Define a function that can "throw an exception", but will catch its own Throw if necessary:
In[4]:= |
In[5]:= |
Out[5]= |
In[6]:= |
Out[6]= |
With no outer NestedCatch, the individual values are returned:
In[7]:= |
Out[7]= |
Wrap in an additional NestedCatch so that the Throw will propagate to the top level:
In[8]:= |
Out[8]= |
The Throw only propagates upwards to the outermost NestedCatch; the usual Catch is unaffected:
In[9]:= |
Out[9]= |
In[10]:= |
In[11]:= |
Out[11]= |
The outermost enclosing NestedCatch catches the Throw:
In[12]:= |
Out[12]= |
Compare to Catch, where the nearest enclosing Catch catches the Throw:
In[13]:= |
Out[13]= |
NestedCatch picks up the first Throw that is evaluated:
In[14]:= |
Out[14]= |
A function that can throw a number of different exceptions:
In[15]:= |
A handler for the possible exceptions:
In[16]:= |
In[17]:= |
In[18]:= |
Out[18]= |
Propagate a particular exception upwards with an outer NestedCatch:
In[19]:= |
In[20]:= |
In[21]:= |
Out[21]= |
The inner NestedCatch catches the Throw:
In[22]:= |
Out[22]= |
The outer NestedCatch catches the Throw:
In[23]:= |
Out[23]= |
As long as the tag matches the form being caught, the Throw will continue to propagate upwards:
In[24]:= |
Out[24]= |
Write a set of functions that each handle errors at the top level:
In[25]:= |
In[26]:= |
Since the Throw propagates to the top, only one message is printed for each top-calling function:
In[27]:= |
Out[27]= |
In[28]:= |
Out[28]= |
In[29]:= |
Out[29]= |
In[30]:= |
Out[30]= |
This work is licensed under a Creative Commons Attribution 4.0 International License