I was all excited when I was able to consolidate a lot of try/catch logic behind a macro earlier this morning. All was good.
I felt like I could do a better job of communicating my intentions in the code though with a rethrow construct rather than writing
(catch FooException #f (throw #f))
I would have liked to have been able to simply write
(rethrow FooException)
This failed. Poking around the docs a bit, I see that try/catch is a special form. Which makes sense.
user=> (defmacro rethrow [ex-class] `(catch ~ex-class x# (throw x#)))
#'user/rethrow
user=> (defmacro handle-ex [message & body] `(try ~@body (rethrow IllegalArgumentException) (catch Exception x# (throw (IllegalArgumentException. message)))))
#'user/handle-ex
user=> (handle-ex "no" (throw (IllegalArgumentException. "yes")))
CompilerException java.lang.RuntimeException: Unable to resolve symbol: catch in this context, compiling:(NO_SOURCE_PATH:1:1)
It was a longshot, but I tried to qualify catch. That fails too, because it's not really there...
user=> (defmacro rethrow [ex-class] `(clojure.core/catch ~ex-class x# (throw x#)))
#'user/rethrow
user=> (defmacro handle-ex [message & body] `(try ~@body (rethrow IllegalArgumentException) (catch Exception x# (throw (IllegalArgumentException. message)))))
#'user/handle-ex
user=> (handle-ex "no" (throw (IllegalArgumentException. "yes")))
CompilerException java.lang.RuntimeException: No such var: clojure.core/catch, compiling:(NO_SOURCE_PATH:1:1)
Is this possible to do within the normal bounds of the language?
Thanks!