On Wed, May 21, 2014 at 07:53:18PM -0700, David Gartner wrote: > (defn div [x y] > (/ x y)) > > (defn throw-catch [f] > [(try > (f) > (catch ArithmeticException e "No dividing by zero!") > (catch Exception e (str "You are so bad " (.getMessage e))) > (finally (println "returning... ")))]) > > ... > > Can anyone enlighten me?
So, your issue is that your "div" function expects two arguments, while
your "throw-catch" function calls it (although with the name "f") with
zero arguments. Using an anonymous function like #(div 10 5) creates a
new function of zero arguments which then calls your "div" function with
its two arguments.
So, you should find that this will work for your "div" function:
(defn throw-catch-2 [f a b]
(try
(f a b)
(catch ArithmeticException e "No dividing by zero!")
(catch Exception e (str "You are so bad " (.getMessage e)))
(finally (println "returning... "))))
(throw-catch-2 div 10 5)
To do this more generally, we can use clojure's rest arguments and
"apply" to make this work:
(defn throw-catch-many [f & args]
(try
(apply f args)
(catch ArithmeticException e "No dividing by zero!")
(catch Exception e (str "You are so bad " (.getMessage e)))
(finally (println "returning... "))))
(throw-catch-many div 10 5)
(throw-catch-many #(div 10 5))
You can even just use "/" as your function name now, if you'd like:
(throw-catch-many / 10 5)
(throw-catch-many / 10 0)
signature.asc
Description: Digital signature
