确保执行(finally)

异常处理

(defn throw-if-true [param]
  (try
    (when param
      (throw (ex-info "test exception" {})))
    (catch Exception e
      (println "catch"))
    (finally
      (println "finally"))))

(throw-if-true true)
;; 输出 "catch" 和 "finally"
(throw-if-true false)
;; 只输出 "finally"

;; with-open 是处理资源的惯用写法:
;; 即使函数体抛出异常,也会调用 .close
(with-open [w (java.io.StringWriter.)]
  (.write w "closed anyway")
  (println (str w)))