我用 Java 编写了一个自己的 Exception(名为 MyOwnException
)类:
package com.stackoverflow.clojure;
import java.lang.RuntimeException;
public class MyOwnException extends RuntimeException {
private static final long serialVersionUID = 3020795659981708312L;
public MyOwnException(String s) {
super("My own exception says: " + s);
}
}
现在我想在我的 Clojure 代码中使用 MyOwnException
。我尝试了几件事,但总是出现找不到类异常(.java
和 .clj
位于同一个包com.stackoverflow.clojure
):
(ns com.stackoverflow.clojure.testForOwnExceptions)
;(import '[com.stackoverflow.clojure MyOwnException])
(defn casetest [x]
(case x
"a" "An a."
"b" "A b."
; (-> (clojure.core/format "Expression '%s' not defined." x)(MyOwnException.)(throw))
; (-> (clojure.core/format "Expression '%s' not defined." x)(com.stackoverflow.clojure.MyOwnException.)(throw))
(-> (clojure.core/format "Expression '%s' not defined." x)(IllegalArgumentException.)(throw))
))
;(prn(casetest "error"))
除此之外:纯粹使用 Clojure 的解决方案会是什么样子? (Exception类的定义+用法)
更新(project.clj):
(defproject com.stackoverflow.clojure/tests "0.1.0-SNAPSHOT"
:description "Tests of Clojure test-framework."
:url "http://example.com/FIXME"
:license {:name "Eclipse Public License"
:url "http://www.eclipse.org/legal/epl-v10.html"}
:dependencies [[org.clojure/clojure "1.6.0"]
[instaparse "1.3.4"]]
:source-paths ["src/main/clojure"]
:java-source-paths ["src/main/java"]
:test-paths ["src/test/clojure"]
:java-test-paths ["src/test/java"]
)
最佳答案
你是如何运行你的代码的?您是否先编译 Java 源代码?编译后,Java类文件是否在类路径中?
我建议使用 Leiningen 并为您的源使用不同的结构。不要在一个包中混合源。例如 src/main/java
和 src/main/clojure'
。
关于java - 如何在 Clojure 中使用自己的 Java 异常类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26358839/