下面的代码片段都不适用于clojure 1.6.0
(try
(prn vv)
(catch clojure.lang.ExceptionInfo e (prn "catch e: " e))
(finally (prn "finally") )
)
我在这里阅读了其他一些帖子之后也试过这个:
(try
(doall (prn vv))
(catch clojure.lang.ExceptionInfo e (prn "catch e: " e))
(finally (prn "finally") )
)
我错过了什么?
麦克
答案 0 :(得分:22)
捕获ExceptionInfo只会捕获使用ex-info:
创建的throwable(try
(throw (ex-info "bad" {:a 1 :b 2}))
(catch clojure.lang.ExceptionInfo e
(prn "caught" e)))
;; => "caught" #<ExceptionInfo clojure.lang.ExceptionInfo: bad {:b 2, :a 1}>
但不是其他例外:
(try
(/ 1 "0")
(catch clojure.lang.ExceptionInfo e
(prn "caught" e)))
;; => ClassCastException java.lang.String cannot be cast to java.lang.Number clojure.lang.Numbers.divide (Numbers.java:155)
你会发现这样:
(try
(/ 1 "0")
(catch Exception e
(prn "caught" e)))
;; => "caught" #<ClassCastException java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Number>
编译异常在评估之前发生:
(try
w is undefined
(catch Exception e
(prn "caught" e)))
;; => CompilerException java.lang.RuntimeException: Unable to resolve symbol: w in this context, compiling:(/private/var/folders/8r/y2d3thln6s3fyrl_s6vknb440000gn/T/form-init6601588363347445596.clj:1:5)
(try
(eval 'w)
(catch Exception e
(prn "caught" e)))
;; => "caught" #<CompilerException java.lang.RuntimeException: Unable to resolve symbol: w in this context, compiling:(/private/var/folders/8r/y2d3thln6s3fyrl_s6vknb440000gn/T/form-init6601588363347445596.clj:1:5)>
您还可以使用多个catch子句来处理不同类型的异常。