Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure not catching NumberFormatException

In the following code, Clojure (1.2) is printing the wrong message:

(try
  (let [value "1,a"]
    (map #(Integer/parseInt %) (.split value ",")))
  (catch NumberFormatException _ (println "illegal argument")))

This should print "illegal argument", but instead it prints a (1#<NumberFormatException java.lang.NumberFormatException: For input string: "a">.

What am I doing wrong?

Is this because of the lazy sequence returned by map? How should it be written?

like image 224
Ralph Avatar asked Feb 05 '11 17:02

Ralph


1 Answers

The try special form only catches exceptions that are raised during during the dynamic extent of the body code. Here map is returning a lazy sequence, which then is passed out of the try special form and returned. The printer then evaluates the sequence, and at that point the exception is thrown.

Wrapping the map in doall should fix your problem.

like image 63
Brian Avatar answered Sep 18 '22 18:09

Brian