On Mon, Jan 24, 2011 at 10:32 AM, Ryan Waters <ryan.or...@gmail.com> wrote:
> The following code doesn't catch the exception thrown like I think it
> should.  Any recommendations appreciated.
>
> https://gist.github.com/793340
>
> Thank you,
> Ryan
>
> - - - -
>
> (ns my-ns
>  (:use [clj-time.core :only [date-time]]))
>
> (defn my-date-time
>  "same as clj-time.core date-time but returns nil on improper input"
>  [& args]
>  (try
>    (apply date-time (map #(Integer/parseInt %) args))
>    (catch NumberFormatException e "hi")))

You're catching NumberFormatException.

> Exception in thread "main" java.lang.RuntimeException

but it's throwing a RuntimeException that wraps your NumberFormatException.

Unfortunately it's difficult to catch specific exceptions in Clojure
due to this wrapping. (I'm not sure why the wrapping is done; all the
invoke methods in IFn are declared with "throws Exception" so it seems
unnecessary.)

Usually you just catch Exception and, during debugging at least, log
the actual exception caught in case it wasn't what you expected -- for
instance, if you got an RTE wrapping an IndexOutOfBoundsException and
the expected exception types were NumberFormatException and
MalformedURLException, it would point to some screwy (nth v index)
usage or another bug.

If there is no function call boundary between the throw and catch, no
wrapping should occur, so

(let [url
  (try (URL. in-string)
    (catch MalformedURLException _)))

should produce a URL object normally and nil on malformed input.

Another option in your case is to replace your #(Integer/parseInt %)
with a different function:

(defn get-int [str]
  (try (Integer/parseInt str)
    (catch NumberFormatException _)))

This will return nil for malformed numbers. How date-time will respond
to nil inputs, I'm not sure, but you may want to be on the lookout for
NullPointerException in your outer, pre-existing catch. :)

-- 
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clojure@googlegroups.com
Note that posts from new members are moderated - please be patient with your 
first post.
To unsubscribe from this group, send email to
clojure+unsubscr...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en

Reply via email to