O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Exceptions and Error Handling

Clojure reuses the JVM’s exception machinery in toto,[282] with its familiar try/catch/finally/throw idiom. Thus, the pattern of error handling in Clojure will be familiar to anyone who has ever worked with languages that share that idiom, including Java, Ruby, Python, and many others.

Given that, blocks of code in Example 9-7 are equivalent with regard to their error handling:

Example 9-7. Parsing a string as an integer in Java, Ruby, and Clojure, with error handling

// Java
public static Integer asInt (String s) {
    try {
        return Integer.parseInt(s);
    } catch (NumberFormatException e) {
        e.printStackTrace();
        return null;
    } finally {
        System.out.println("Attempted to parse as integer: " + s);
    }
}

# Ruby
def as_int (s)
    begin
        return Integer(s)
    rescue Exception => e
        puts e.backtrace
    ensure
        puts "Attempted to parse as integer: " + s
    end
end

; Clojure
(defn as-int
  [s]
  (try
    (Integer/parseInt s)
    (catch NumberFormatException e
      (.printStackTrace e))
    (finally
      (println "Attempted to parse as integer: " s))))

Parsing integers is a pretty mundane operation, but it makes it clear that the semantics and function of the try, catch, and finally forms in Clojure mirror those in Java and, for example, the corresponding ones in Ruby (begin, rescue, ensure):

try

Delimits the scope of an exception-handling form. It may contain any number of catch forms and an optional finally form, all prefixed by any number of expressions that represent the code’s “happy path.”[283] Assuming that ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required