Wolfram Function Repository
Instant-use add-on functions for the Wolfram Language
Function Repository Resource:
Wrapper that combines the functionalities of Catch and Enclose
ResourceFunction["CatchEnclose"][expr,f,handler] uses handler in the enclosing Enclose to handle generated failures. |
CatchEnclose is used just like Enclose:
In[1]:= |
Out[1]= |
In[2]:= |
Out[2]= |
However, any instance of a single-argument Throw will be caught as well:
In[3]:= |
Out[3]= |
Untagged Throws inside CatchEnclose will NOT be caught by other instances of Catch:
In[4]:= |
Out[4]= |
Tagged Throws still need their custom Catch statements to be caught:
In[5]:= |
Out[5]= |
Throws with custom tags will be invisible to CatchEnclose:
In[6]:= |
Out[6]= |
In[7]:= |
Out[7]= |
The function in the second argument can still use Confirm and related constructs to validate the thrown value:
In[8]:= |
Out[8]= |
In[9]:= |
Out[9]= |
The third argument function will be applied to any error generated by Confirm-like constructs:
In[10]:= |
Out[10]= |
Just like the lexical version of Enclose, CatchEnclose can be slow if you insert large amounts of data into the body. This happens frequently with functions that take data. For example, here is a function that checks that a lists starts with integers until it hits an even number:
In[11]:= |
Test the function:
In[12]:= |
Out[12]= |
In[13]:= |
Out[13]= |
In[14]:= |
Out[14]= |
The function is quite slow for large lists because of the way that the body of CatchEnclose needs to be scanned for lexical instances of Throw and Confirm:
In[15]:= |
Out[16]= |
In most cases, this problem can be easily avoided by making sure that the data inserted from the left-hand-side of the assignment is not directly inside of CatchEnclose, but instead copied into a Module variable outside of CatchEnclose:
In[17]:= |
This implementation is significantly faster:
In[18]:= |
Out[18]= |
This work is licensed under a Creative Commons Attribution 4.0 International License