Clojure学习入门(17)—— 异常处理
8,204 views
0
异常处理
Clojure代码里面抛出来的异常,都是运行时异常。因为其是函数式编程、解释型执行。
当然,从Clojure代码里面调用的java代码还是可能抛出那种需要检查的异常的。
try - catch - finally 以及throw 提供了和java里面类似的功能。
try、catch、throw、finally:
user=> (try (throw (Exception. "error")) (finally (println "final"))) final Exception error user/eval310 (NO_SOURCE_FILE:1) user=> (try (/ 3 0) (catch Exception e (println e))) #<ArithmeticException java.lang.ArithmeticException: Divide by zero> nil
assert:
它测试一个表达式, 如果这个表达式的值为false的话,它会抛出异常。
user=> (assert true) nil user=> (assert false) AssertionError Assert failed: false user/eval317 (NO_SOURCE_FILE:1) user=> (assert nil) AssertionError Assert failed: nil user/eval319 (NO_SOURCE_FILE:1) user=> (assert 0) nil user=> (assert [1 2 3]) nil user=> (assert "foo") nil
Clojure 完整示例:
(ns helloclojure.myexception)
(defn exception_test1 []
(try (throw (Exception. "--error--"))
(finally (println "final"))
))
(defn exception_test2 []
(try (/ 3 0)
(catch Exception e (println "error: " e))
))
(defn exception_test3 [cls]
(try (Class/forName cls) true
(catch ClassNotFoundException e false))
)
;(exception_test1)
(exception_test2) ; error: #<ArithmeticException java.lang.ArithmeticException: Divide by zero>
;(exception_test3 helloclojure.myexception)
(assert true)
;(assert false)
;(try (assert false)
; (catch Exception e (println "error" e))
; (finally (println 'finally)))
;(assert nil)
(assert [1 2 3])
(assert "foo")
(assert 0)
(print 'end)
参考推荐:
版权所有: 本文系米扑博客原创、转载、摘录,或修订后发表,最后更新于 2024-08-08 16:23:59
侵权处理: 本个人博客,不盈利,若侵犯了您的作品权,请联系博主删除,莫恶意,索钱财,感谢!