如何在Clojure中使用自己的Java-Exception类?

时间:2014-10-14 10:43:41

标签: java exception exception-handling clojure

我在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。我尝试了几件事,但我总是遇到Class not found例外(.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中的解决方案怎么样? (异常类+用法的定义)

更新(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"]
  )

2 个答案:

答案 0 :(得分:2)

您如何运行代码?您是在先编译Java源代码吗?编译后,Java类文件是否在类路径中?

我建议使用Leiningen并为您的来源使用不同的结构。不要在一个包装中混合来源。请举例src/main/javasrc/main/clojure'

请查看:Polyglot (Clojure, Java) Projects With Leiningen

答案 1 :(得分:1)

使用

(import '[com.stackoverflow.clojure MyOwnException])

应与

一起使用
...
(-> (clojure.core/format "Expression '%s' not defined." x)(MyOwnException.)(throw))
...

或单独的完全限定名称:

...
(-> (clojure.core/format "Expression '%s' not defined." x)(com.stackoverflow.clojure.MyOwnException.)(throw))
...

由于你的问题中已经有了正确的代码(已经过了评论的部分),我猜你的REPL出了问题。也许你应该在运行以下代码组合之前重新启动它。 请记住:只运行(prn(casetest "error"))不会自动更改函数的代码。您必须将完整的新代码发送到REPL(例如,通过使用Run as / Clojure Application)

(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))
    ))

(prn(casetest "error"))

(ns com.stackoverflow.clojure.testForOwnExceptions)

(defn casetest [x]
  (case x
    "a" "An a."
    "b" "A b."
    (-> (clojure.core/format "Expression '%s' not defined." x)(MyOwnException.)(throw))
    ))

(prn(casetest "error"))