Today I will be looking at exception handling. Clojure provides the normal try-catch-finally block to catch exceptions and has the following general syntax
(try
(code)
catch Exception e1)
(Exception Handler)
(finally
Cleanup code)
Here is an example
(try
(/ 2 0)
(catch ArithmeticException e
"divide by zero")
(finally
(println "cleanup code")))
cleanup code
=> "divide by zero"
You can throw an exception in the following manner
(try
(throw (ex-info "There was a problem" {:causes "example"}))
(catch Exception e
(println ex-data e)))
#object[clojure.core$ex_data 0x5f1df0de clojure.core$ex_data@5f1df0de] #error {
:cause There was a problem
:data {:causes example}
:via
[{:type clojure.lang.ExceptionInfo
:message There was a problem
:data {:causes example}
:at [leinproj.core$eval1739 invokeStatic form-init10068916269700534711.clj 2]}]
:trace
[[leinproj.core$eval1739 invokeStatic form-init10068916269700534711.clj 2]
[leinproj.core$eval1739 invoke form-init10068916269700534711.clj 1]
[clojure.lang.Compiler eval Compiler.java 7177]
[clojure.lang.Compiler eval Compiler.java 7132]
[clojure.core$eval invokeStatic core.clj 3214]
[clojure.core$eval invoke core.clj 3210]
[clojure.main$repl$read_eval_print__9086$fn__9089 invoke main.clj 437]
[clojure.main$repl$read_eval_print__9086 invoke main.clj 437]
[clojure.main$repl$fn__9095 invoke main.clj 458]
[clojure.main$repl invokeStatic main.clj 458]
[clojure.main$repl doInvoke main.clj 368]
[clojure.lang.RestFn invoke RestFn.java 1523]
[nrepl.middleware.interruptible_eval$evaluate invokeStatic interruptible_eval.clj 79]
[nrepl.middleware.interruptible_eval$evaluate invoke interruptible_eval.clj 55]
[nrepl.middleware.interruptible_eval$interruptible_eval$fn__971$fn__975 invoke interruptible_eval.clj 142]
[clojure.lang.AFn run AFn.java 22]
[nrepl.middleware.session$session_exec$main_loop__1072$fn__1076 invoke session.clj 171]
[nrepl.middleware.session$session_exec$main_loop__1072 invoke session.clj 170]
[clojure.lang.AFn run AFn.java 22]
[java.lang.Thread run Thread.java 832]]}
=> nil
ex-info can contain a message and a map, and ex-data allows you to retrieve the map or return nil if not created with an ex-info.
(println “Bye 4 Now!")
No comments:
Post a Comment