An alternate way of doing it:
(defmacro maybe
[& body]
`(try [(do ~@body) nil]
(catch Exception e#
[nil e#])))
(defn repeat-exec
([f]
(let [run (fn g[] (cons (f) (lazy-seq (g))))]
(run)))
([n f]
(take n (repeat-exec f))))
(defmacro try-times
[n & body]
`(let [f# #(first (maybe ~@body))
c# (repeat-exec (dec ~n) f#)
r# (some identity c#)]
(or r# (do ~@body))))
Putting it into action:
(defn f
"The sample function we want to try several times"
[]
(println "x ")
(str "y " "z ")
(throw (NullPointerException. "boom ")))
(try-times 10 (f))
Hope this helps.
Regards,
Shantanu
On Mar 18, 6:49 am, Fiel Cabral
<[email protected]> wrote:
> Hello Clojure users,
> This is a dumb question but I'd like to write something equivalent to this
> in Clojure:
>
> public String loop_with_exception(int retries)
> {
> for (int n = retries; n > 0; n--) {
> try {
> return some_io_operation();
> } catch (IOException e) {
> continue;
> }
> }
> return null;
>
> }
>
> So I tried writing it like this:
>
> (ns sandbox.core
> (:import [java.io.IOException]))
>
> (defn some-io-operation
> "Some read I/O operation that could throw an IOException."
> []
> (println "WOULD do a read operation"))
>
> (defn loop-with-exception [retries]
> (loop [n retries]
> (try
> (when (pos? n)
> (some-io-operation))
> (catch IOException e
> (recur (dec n))))))
>
> But I get this error:
>
> cd c:/EMACSHOME/CLOJURE-PROJECTS/sandbox/src/sandbox/
> 1 compiler notes:
>
> Unknown location:
> error: java.lang.UnsupportedOperationException: Cannot recur from
> catch/finally
>
> core.clj:13:9:
> error: java.lang.UnsupportedOperationException: Cannot recur from
> catch/finally (core.clj:13)
>
> Compilation failed.
>
> What's the recommended way to handle exceptions and retry inside a
> loop/recur?
>
> Thank you.
>
> -Fiel Cab.ral
--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to [email protected]
Note that posts from new members are moderated - please be patient with your
first post.
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en