How can I throw an exception in Clojure?

You need to wrap your string in a Throwable:

(throw (Throwable. "Some text"))

or

(throw (Exception. "Some text"))

You can set up a try/catch/finally block as well:

(defn myDivision [x y]
  (try
    (/ x y)
    (catch ArithmeticException e
      (println "Exception message: " (.getMessage e)))
    (finally 
      (println "Done."))))

REPL session:

user=> (myDivision 4 2)
Done.
2
user=> (myDivision 4 0)
Exception message:  Divide by zero
Done.
nil

Leave a Comment