Skip to content

Instantly share code, notes, and snippets.

@Gonzih
Last active April 11, 2017 14:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Gonzih/5814945 to your computer and use it in GitHub Desktop.
Save Gonzih/5814945 to your computer and use it in GitHub Desktop.
Clojure try* macro experiment. Part of small project that I'm working on right now (https://github.com/Gonzih/feeds2imap.clj).
(defmacro try*
"Macro to catch multiple exceptions with one catch body.
Usage:
(try*
(println :a)
(println :b)
(catch* [A B] e (println (class e)))
(catch C e (println :C))
(finally (println :finally-clause)))
Will be expanded to:
(try
(println :a)
(println :b)
(catch A e (println (class e)))
(catch B e (println (class e)))
(catch C e (println :C))
(finally (println :finally-clause)))
"
[& body]
(letfn [(catch*? [form]
(and (seq form)
(= (first form) 'catch*)))
(expand [[_catch* classes & catch-tail]]
(map #(list* 'catch % catch-tail) classes))
(transform [form]
(if (catch*? form)
(expand form)
[form]))]
(cons 'try (mapcat transform body))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment