Clojure 学习 —— 异常处理

clojure 异常处理简单介绍及示常见函数(宏)示例

一、异常处理

Clojure代码里面抛出来的异常都是运行时异常。当然从Clojure代码里面调用的java代码还是可能抛出那种需要检查的异常的。

try - catch - finally 以及throw 提供了和java里面类似的功能。

trycatchthrowfinally

1
2
3
4
5
6
7
8
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的话,它会抛出异常。

1
2
3
4
5
6
7
8
9
10
11
12
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)

二、参考资料
Clojure 学习入门(17)—— 异常处理
clojure-基本语法-流程控制(二)

文章目录
  1. 1. 一、异常处理