Exceptionally good

Clojure interacts really well with the JVM. Exceptions in Clojure are simply implemented as standard Java exceptions, and there are special forms for throwing exceptions and for doing the normal try-catch-finally exception handling pattern.

Nomal Java exceptions can be thrown by most expressions
user=> (/ 1 0)
java.lang.ArithmeticException: Divide by zero (NO_SOURCE_FILE:0)

And we can also easily create instances of Exception classes and throw these using the throw special form.
user=> (throw (Exception.))
java.lang.Exception (NO_SOURCE_FILE:0)

The REPL also catches exceptions when it evaluates the form it has just read. This code binds the exception into a Var so that it can be examined.
         (try
           (let [input (read request-prompt request-exit)]
             (or (#{request-prompt request-exit} input)
                 (let [value (eval input)]
                   (print value)
                   (set! *3 *2)
                   (set! *2 *1)
                   (set! *1 value))))
           (catch Throwable e
             (caught e)
             (set! *e e)))

This gives the behaviour
user=> (throw (Exception.))
java.lang.Exception (NO_SOURCE_FILE:0)
user=> (bean *e)
{:stackTrace #<StackTraceElement[] [Ljava.lang.StackTraceElement;@9ba134>, :message "java.lang.Exception (NO_SOURCE_FILE:0)", :localizedMessage "java.lang.Exception (NO_SOURCE_FILE:0)", :class clojure.lang.Compiler$CompilerException, :cause #<Exception java.lang.Exception>}

try-catch-finally takes the form with the usual semantics. The first clause is found which handles the class of the exception, and this clause is used to process the exception, binding a local variable to the handled exception. Any finally clause is executed on exit from the scope.

(try
  (/ 1 0)
(catch ArithmeticException e (println "Arithmetic exception"))
(catch Throwable e (println "Throwable"))
(finally
    (println "Done")))

Advertisements
This entry was posted in Computers and Internet. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s