如何捕获编译时异常? [英] How to catch a compile-time exception?
问题描述
在Clojure中是否有可能捕获在编译时发生的异常?对于运行时异常,使用try / catch很容易,但是假设我有:
Is it possible in Clojure to catch an exception that occurs at compile time? Using try/catch is fine and easy for run-time exceptions, but suppose I have:
(defmacro will-throw-at-compile [] (assert false "it threw"))
(try (will-throw-at-compile) (catch Exception e "caught it"))
我找不到任何办法可以抓住这一点,但是抓不到。我也尝试过不同类型的异常类,这似乎不是问题。
I can't find any way to catch this, the catch never happens. I've tried different types of exception classes as well, doesn't seem to be the problem.
我还认为,由于上述尝试是运行时调用,使宏在编译时进行尝试:
I also thought that since the try above is a run-time call, making a macro to do the try at compile time:
(defmacro t [x] (try x (catch Exception e "caught it")))
也不起作用:
(t (will-throw-at-compile))
也许无法完成?
推荐答案
如果宏能够处理其自身的异常,则可以使其工作。将宏的大部分工作分解为一个函数:
You can make it work if the macro handles it's own exception. Break out the majority of the work of the macro into a function:
(defn thrower []
(throw (Exception. "it threw")))
(defmacro will-throw
[]
(try
(thrower)
(catch Exception e (println "caught it")))
(println "leaving macro"))
(will-throw)
运行此代码将导致:
> lein run
caught it
leaving macro
将所有宏功能转换为常规功能,因此可以将其称为&在编译时宏机制之外进行了测试。然后,您可以使用常规的单元测试,如下所示:
The idea is to put most or all of the macro functionality into a regular function, so it can be called & tested outside of the compile-time macro mechanism. Then you can use regular unit-tests like so:
(deftest t-thrower
(is (thrown? Exception (thrower)))
(println "t-thrower complete"))
> lein test
caught it
leaving macro
lein test tst.clj.core
t-thrower complete
Ran 1 tests containing 1 assertions.
0 failures, 0 errors.
这篇关于如何捕获编译时异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!