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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With