philipbohun.com

Glojure by Example: Exceptions

throw raises an exception. ex-info builds one that carries a message and a data map. catch selects by type. ExceptionInfo is the type ex-info produces. finally runs on the way out, which is the usual replacement for Go's defer.

(defn parse [s]
  (let [n (parse-long s)]
    (if (nil? n)
      (throw (ex-info "not a number" {:input s}))
      n)))

(require '[clojure.string :as string])

(defn run [s]
  (try
    (println "value" (parse s))
    (catch ExceptionInfo e
      (println "error"
               (first (string/split-lines (ex-message e)))
               (pr-str (ex-data e))))
    (finally
      (println "done" s))))

Go functions do not raise for an ordinary failure. They return an error value, covered on the multiple-return-values page. panic and recover are not the Glojure control-flow tools. Catch with go/any when the type does not matter.

(run "42")
(run "nope")

finally prints after both the success path and the catch path.

$ glj exceptions.glj
value 42
done 42
error not a number {:input "nope"}
done nope

Next example: Go Packages.