gpt4 book ai didi

Clojure:如何在异常时重现?

转载 作者:行者123 更新时间:2023-12-03 07:17:54 24 4
gpt4 key购买 nike

在因异常而放弃之前,我尝试多次执行函数。但在 Clojure 中从 catch block 中重复是无效的。如何才能实现这一目标?

(loop [tries 10]
(try
(might-throw-exception)
(catch Exception e
(when (pos? tries) (recur (dec tries))))))

java.lang.UnsupportedOperationException: Cannot recur from catch/finally

我能找到的最好的是以下笨拙的解决方案(包装在 func 中并调用它)

(defn do-it []
(try
(might-throw-exception)
(catch Exception e nil)))

(loop [times 10]
(when (and (nil? (do-it)) (pos? times))
(recur (dec times))))

最佳答案

宏正在调用...

这个怎么样:

(defn try-times*
"Executes thunk. If an exception is thrown, will retry. At most n retries
are done. If still some exception is thrown it is bubbled upwards in
the call chain."
[n thunk]
(loop [n n]
(if-let [result (try
[(thunk)]
(catch Exception e
(when (zero? n)
(throw e))))]
(result 0)
(recur (dec n)))))

(defmacro try-times
"Executes body. If an exception is thrown, will retry. At most n retries
are done. If still some exception is thrown it is bubbled upwards in
the call chain."
[n & body]
`(try-times* ~n (fn [] ~@body)))

关于Clojure:如何在异常时重现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879885/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com