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"))
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.
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