Clojure その15
今回は try-catch です
とりあえずなんらかのExceptionを吐き出してくれる処理を用意します
(ns hello.core) (defn -main [x y] (println x "/" y "=" (/ (Integer. x) (Integer. y))))
エラーを起こす方法は簡単
ゼロで割ってやれば良いです
$ lein run 2 0 Exception in thread "main" java.lang.ArithmeticException: Divide by zero at clojure.lang.Numbers.divide(Numbers.java:156) at hello.core$_main.invoke(core.clj:4) at clojure.lang.Var.invoke(Var.java:419) at user$eval5$fn__7.invoke(form-init7771791051060385950.clj:1) at user$eval5.invoke(form-init7771791051060385950.clj:1) at clojure.lang.Compiler.eval(Compiler.java:6619) at clojure.lang.Compiler.eval(Compiler.java:6609) at clojure.lang.Compiler.load(Compiler.java:7064) at clojure.lang.Compiler.loadFile(Compiler.java:7020) at clojure.main$load_script.invoke(main.clj:294) at clojure.main$init_opt.invoke(main.clj:299) at clojure.main$initialize.invoke(main.clj:327) at clojure.main$null_opt.invoke(main.clj:362) at clojure.main$main.doInvoke(main.clj:440) at clojure.lang.RestFn.invoke(RestFn.java:421) at clojure.lang.Var.invoke(Var.java:419) at clojure.lang.AFn.applyToHelper(AFn.java:163) at clojure.lang.Var.applyTo(Var.java:532) at clojure.main.main(main.java:37)
では先程のものに try-catch を追加してみます
(ns hello.core) (defn -main [x y] (try (println x "/" y "=" (/ (Integer. x) (Integer. y))) (catch ArithmeticException e (println (.getMessage e)))) )
$ lein run 2 0 Divide by zero
おぉ!きちんと動いた!
finally も追加してみよう
(ns hello.core) (defn -main [x y] (try (println x "/" y "=" (/ (Integer. x) (Integer. y))) (catch ArithmeticException e (println (.getMessage e))) (finally (println "finally"))) )
$ lein run 2 0 Divide by zero finally
Excellent!
- アーティスト: 堀江由衣
- 出版社/メーカー: キングレコード
- 発売日: 2013/11/13
- メディア: CD
- この商品を含むブログ (23件) を見る