5

I'm trying to catch an exception that is thrown by a function passed to a map function but it isn't caught. I don't understand why.

Example:

(defn x [x]
  (throw (Exception. "An exception")))

(try
  (map x '(1 2 3))
  (catch Exception e "caught exception"))
0

1 Answer 1

7

You are being hit by lazyness. Remember, map returns a lazy seq, therefore x isn't run until something tries to access the first element of that seq.

Your example will work if you realize it with some fn, let's say doall, or first, like so:

(try
  (doall (map x [1 2 3]))
  (catch Exception e "Caught!"))

Then why do you receive the exception at all? Well since no exceptions are raised, the try block returns the lazy seq, which your REPL will try to print out, calling x for you.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.