在Clojure中是否可以捕获编译时发生的异常?使用try / catch对运行时异常很简单,但假设我有:
<android.support.percent.PercentRelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fifty_huntv"
android:background="#ff7acfff"
android:text="20% - 50%"
android:textColor="@android:color/white"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_heightPercent="20%"
app:layout_widthPercent="50%" />
<TextView
android:layout_toRightOf="@id/fifty_huntv"
android:background="#ffff5566"
android:text="80%-50%"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_heightPercent="80%"
app:layout_widthPercent="50%"
/>
</android.support.percent.PercentRelativeLayout>
我找不到任何方法来捕捉这个,捕获永远不会发生。我也尝试过不同类型的异常类,似乎不是问题。
我还认为,由于上面的尝试是一个运行时调用,所以让宏在编译时进行尝试:
(defmacro will-throw-at-compile [] (assert false "it threw"))
(try (will-throw-at-compile) (catch Exception e "caught it"))
也不起作用:
(defmacro t [x] (try x (catch Exception e "caught it")))
也许不能做到?
答案 0 :(得分:2)
如果宏处理它自己的异常,你可以使它工作。将宏的大部分工作分解为函数:
(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
我们的想法是将大部分或全部宏功能放入常规功能中,因此可以将其称为&amp;在编译时宏机制之外测试。然后你可以像这样使用常规的单元测试:
(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.