当用户不提供命令行参数时,我希望Hello World打印用法信息而不是错误跟踪。

":";exec clj -m `basename $0 .clj` ${1+"$@"}
":";exit

(ns hello
    (:gen-class))

(defn -main
    [greetee]
    (println (str "Hello " greetee "!")))

$ ./hello.clj Fred
Hello Fred!
$ ./hello.clj
Exception in thread "main" clojure.lang.ArityException: Wrong number of args (0) passed to: hello$-main
    at clojure.lang.AFn.throwArity(AFn.java:439)
    at clojure.lang.AFn.invoke(AFn.java:35)
    at clojure.lang.Var.invoke(Var.java:397)
    at clojure.lang.AFn.applyToHelper(AFn.java:159)
    at clojure.lang.Var.applyTo(Var.java:518)
    at clojure.core$apply.invoke(core.clj:600)
    at clojure.main$main_opt.invoke(main.clj:323)
    at clojure.lang.FnLoaderThunk.invoke(FnLoaderThunk.java:36)
    at clojure.main$main.doInvoke(main.clj:426)
    at clojure.lang.RestFn.invoke(RestFn.java:422)
    at clojure.lang.FnLoaderThunk.invoke(FnLoaderThunk.java:36)
    at clojure.lang.Var.invoke(Var.java:405)
    at clojure.lang.AFn.applyToHelper(AFn.java:165)
    at clojure.lang.Var.applyTo(Var.java:518)
    at clojure.main.main(main.java:37)

最佳答案

(defn -main [& args]
  (if-not (first args)
    (usage)
    (println "Hello" (first args))))

您可以对此进行一些改进,但这是一个合理的轮廓。

关于clojure - 如何避免线程 "main"clojure.lang.ArityException中的异常?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5227543/

10-10 00:56