This is slower but is a bit clearer.

(defn get-with-exception [map key]
  (if (contains? map key)
    (get map key)
    (throw (Exception. "oops"))))

Curious, why do you want to do this? Are you working with Java interop?

Ambrose

On Sun, Mar 20, 2011 at 5:50 PM, Andreas Kostler <
andreas.koestler.le...@gmail.com> wrote:

> Hi all,
> I would like to throw an exception when I'm trying to retrieve a value in a
> map for a key that doesn't exist.
> The obvious first shot was:
> (get {:foo "bar"} :foo (throw (new Exception "Oh no!")))
> However, this doesn't work because the exception always throws since get
> apparently eagerly evaluates it's arguments.
> One way to work around this could be:
>
> (defn get-with-exception [map key]
>            (let [res (get map key (new Exception "my-exception"))]
>                 (if (= (class res) java.lang.Exception)
>                     (throw res)
>                     res)))
>
> I was wondering, is there another more concise/idiomatic way?
>
> Cheers
> Andreas
>
> --
> "Test-driven Dentistry (TDD!) - Not everything should be test driven"
> - Michael Fogus
> --
> **********************************************************
> Andreas Koestler, Software Engineer
> Leica Geosystems Pty Ltd
> 270 Gladstone Road, Dutton Park QLD 4102
> Main: +61 7 3891 9772     Direct: +61 7 3117 8808
> Fax: +61 7 3891 9336
> Email: andreas.koest...@leica-geosystems.com
>
> ************www.leica-geosystems.com*************
>
> when it has to be right, Leica Geosystems
>
> Please  consider the environment before printing this email.
>
> --
> 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

-- 
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