<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0">
<channel>
<title>Clojure Q&amp;A - Recent questions tagged catch</title>
<link>https://ask.clojure.org/index.php/tag/catch</link>
<description></description>
<item>
<title>What is the technical or ideological reason for not allowing `recur` from inside a `catch` block?</title>
<link>https://ask.clojure.org/index.php/13924/technical-ideological-reason-allowing-recur-inside-catch</link>
<description>&lt;p&gt;Currently, it's not possible to &lt;code&gt;recur&lt;/code&gt; across a &lt;code&gt;try&lt;/code&gt; block:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  (let [RETRIABLE-FUNCTION (fn [] (println &quot;Function called&quot;) (throw (ex-info &quot;Function failed&quot; {})))]
    (loop [retries 3]
      (try
        (RETRIABLE-FUNCTION)
        (catch Exception ex
          (when (&amp;lt; 1 retries)
            (recur (dec retries)))))))

Syntax error (UnsupportedOperationException) compiling recur at (src/repl.clj:7:13). Can only recur from tail position
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;So instead on has to rewrite the code as something like this:&lt;/p&gt;
&lt;pre&gt;&lt;code&gt;  (let [RETRIABLE-FUNCTION (fn [] (println &quot;Function called&quot;) (throw (ex-info &quot;Function failed&quot; {})))]
    (loop [retries 3]
      (let [result (try
                     (RETRIABLE-FUNCTION)
                     (catch Exception ex
                       (when (&amp;lt; 1 retries)
                         ::retry)))]
        (if (= ::retry result)
          (recur (dec retries))
          result))))
&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;— which is pretty unwieldy, especially in the cases of nested retries or more complex state machines.&lt;br&gt;
Alternatively, one could use one of many retry macro libraries — which is a pretty heavy price for such simple use case, I think. And usually much less flexible than what one could do in-place.&lt;/p&gt;
&lt;p&gt;&quot;Ideologically&quot;, it seems to me that there should be problem there, as the last expression in catch look to me like a tail position.&lt;/p&gt;
&lt;p&gt;Is there a technical limitation of the JVM that makes the recur-across-try impossible (or maybe has very low performance, so it's a good idea to discourage that)? Or is it just a low-priority quality-of-life feature, so it never got to an implementation?&lt;/p&gt;
</description>
<category>Clojure</category>
<guid isPermaLink="true">https://ask.clojure.org/index.php/13924/technical-ideological-reason-allowing-recur-inside-catch</guid>
<pubDate>Wed, 29 May 2024 07:55:55 +0000</pubDate>
</item>
</channel>
</rss>