Clojure 学习入门(17)—— 异常处理

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

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


try、catch、throw、finally:

  1. user=>(try(throw(Exception."error"))(finally(println"final")))
  2. final
  3. Exceptionerroruser/eval310(NO_SOURCE_FILE:1)

  1. user=>(try(/30)(catchExceptione(printlne)))
  2. #<ArithmeticExceptionjava.lang.ArithmeticException:Dividebyzero>
  3. nil

assert:
它测试一个表达式, 如果这个表达式的值为false的话,它会抛出异常。
  1. user=>(asserttrue)
  2. nil
  3. user=>(assertfalse)
  4. AssertionErrorAssertfailed:falseuser/eval317(NO_SOURCE_FILE:1)
  5. user=>(assertnil)
  6. AssertionErrorAssertfailed:niluser/eval319(NO_SOURCE_FILE:1)
  7. user=>(assert0)
  8. nil
  9. user=>(assert[123])
  10. nil
  11. user=>(assert"foo")
  12. 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)