clojure - 不同类型的异常没有被捕获?

标签 clojure

; common/math.clj
(defn nths
  "Returns a collection of values for each idx in idxs. Throws an error if any one idx is out of bounds."
  [coll idxs]
  (map #(nth coll %) idxs))

; nrepl
common.math> (try (/ 1 0)
     (catch Exception e (prn "in catch"))
     (finally (prn "in finally")))
"in catch"
"in finally"
nil
common.math> (try (nths '(5 6 7 8 9) '(0 5))
     (catch Exception e (prn "in catch"))
     (finally (prn "in finally")))
"in finally"
IndexOutOfBoundsException   clojure.lang.RT.nthFrom (RT.java:784)
common.math> (nths '(5 6 7 8 9) '(0 1 3))
(5 6 8)
common.math> *clojure-version*
{:major 1, :minor 5, :incremental 0, :qualifier "alpha4"}

我无法弄清楚第二个表达式出了什么问题。我期待它会再次打印:

"in catch"
"in finally"

运行单元测试时也会发生同样的情况:

lein test unittest.common.math

FAIL in (test-nths) (math.clj:87)
expected: (thrown? IndexOutOfBoundsException (nths (quote (5 6 7 8 9)) (quote (0 5))))
  actual: nil

应该会通过。

最佳答案

Nths 是惰性的,因此当您的 repl 尝试打印结果时,该函数实际上会运行:

core> (def result (try (nths '(5 6 7 8 9) '(0 5))
                        (catch Exception e (prn "in catch"))
                        (finally (prn "in finally"))))
"in finally"
#'core/result
core> result
; Evaluation aborted.

您可以在nths中捕获异常,或者在使用它时更有意义地捕获它

rsadl.core> (def result (try (nths '(5 6 7 8 9) '(0 5))
                        (catch Exception e (prn "in catch"))
                        (finally (prn "in finally"))))
"in finally"
#'core/result
core> (try (println result) (catch Exception e (prn "in catch")))
("in catch"
nil

或者正如 number23_cn 指出的那样,只要您不需要它因其他原因而变得懒惰,您就可以在创建它时实现结果。

关于clojure - 不同类型的异常没有被捕获?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12151302/

相关文章:

multithreading - 在 clojure 中使用 at-at 库时应用程序不退出

unit-testing - 为什么我不能使用 midje 来模拟使用弹弓的 throw+ 抛出的函数

java - lein环uberjar : PKIX path building failed?

java - 无法从根文件级别导出 Clojure 函数

clojure - 如何测试多组所有组合中的给定总和?

Clojure循环/重复模式,不好用吗?

java - Clojure - 消耗的惰性序列元素是否保留在内存中?

clojure - db.part/db 的所有字段是什么意思?

java - 引用从 Clojure 文件生成的类的 Java 文件的 Leiningen 编译错误

clojure - 包括特定于平台的 java 依赖项(不让我的头发着火)