Skip to content

Instantly share code, notes, and snippets.

@alexpw
Created March 23, 2012 04:28
Show Gist options
  • Save alexpw/2166820 to your computer and use it in GitHub Desktop.
Save alexpw/2166820 to your computer and use it in GitHub Desktop.
Clojure - macro try-catch
;; Approach 1, verbose
(defmacro try-catch [[lvl-fn fn] body]
(list 'try body
(list 'catch 'Exception 'e
(list lvl-fn 'e
(list ':name (list 'meta '#'fn))))))
(macroexpand '(try-catch [info foo] (reduce + 0 (range 5))))
;;=> (try (reduce + 0 (range 5)) (catch Exception e (info e (:name (meta (var fn))))))
;; Approach 2, syntax-quote
(defmacro try-catch [[lvl-fn fn] body]
`(try
~body
(catch Exception e#
(~lvl-fn e# (str "Exception thrown trying to " (:name (meta #'~fn)))))))
(macroexpand '(try-catch [info foo] (throw (new Exception "test"))))
;;=> (try (throw (new Exception "test")) (catch java.lang.Exception e__1427__auto__ (info e__1427__auto__ (clojure.core/str "Exception thrown trying to " (:name (clojure.core/meta (var foo)))))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment