ClojureDocs

Nav

Namespaces

The exprs are evaluated and, if no exceptions occur, the value of the last
is returned. If an exception occurs and catch clauses are provided, each is
examined in turn and the first for which the thrown exception is an instance
of the named class is considered a matching catch clause. If there is a
matching catch clause, its exprs are evaluated in a context in which name is
bound to the thrown exception, and the value of the last is the return value
of the function. If there is no matching catch clause, the exception
propagates out of the function. Before returning, normally or abnormally,
any finally exprs will be evaluated for their side effects. See
http://clojure.org/special_forms for more information.
6 Examples
=> (try
     (/ 1 0)
     (catch Exception e (str "caught exception: " (.getMessage e))))

"caught exception: Divide by zero"
;; for Clojurescript use js/Object as type
(try
   (/ 1 0)
   (catch js/Object e
       (.log js/console e)))
;; Example with multiple catch clauses and a finally clause.
(try (f)
    (catch SQLException se (prn (.getNextException e)))
    (catch Exception2 e (prn "Handle generic exception"))
    (finally (prn "Release some resource")))
;; The catch/finally clause is an implicit do.
(try
  (/ 1 0)
  (catch Exception ex 
     (.printStackTrace ex)
     (str "caught exception: " (.getMessage ex))))
;; java.lang.ArithmeticException: Divide by zero
;;	at clojure.lang.Numbers.divide(Numbers.java:163)
;;	at clojure.lang.Numbers.divide(Numbers.java:3833)
;; ...
;;      at main.java:37)
;;=> "caught exception: Divide by zero"
;; try multiple expressions
(try (println "expression 1")
     (println "expression 2")
     (/ 1 0)
     (println "expression 4")
     (catch Exception e (println "expression 3 throws")))
;;=> expression 1
;;=> expression 2
;;=> expression 3 throws
;; The last value in the body of try will be returned.
(try "I will not be returned."
     "I will be returned"
     (catch Exception e (.getMessage e))
     (finally "I will also not be returned."))
;; => "I will be returned"

;; If there's an exception the last value in the body of catch will be returned.
(try (throw (RuntimeException.))
     "I will not be returned"
     (catch Exception e "I will be returned")
     (finally "I will also not be returned."))
;; => "I will be returned"
See Also

The exprs are evaluated and, if no exceptions occur, the value of the last is returned. If an except...

Added by zk

The exprs are evaluated and, if no exceptions occur, the value of the last is returned. If an except...

Added by klauern

The expr is evaluated and thrown, therefore it should yield an instance of some derivee of Throwable...

Added by klauern

Create an instance of ExceptionInfo, a RuntimeException subclass that carries a map of additional...

Added by MicahElliott

Returns exception data (a map) if ex is an IExceptionInfo. Otherwise returns nil.

Added by MicahElliott
0 Notes
No notes for try