Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot catch exception inside map function [duplicate]

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"))
like image 933
pressbyron Avatar asked Mar 14 '23 14:03

pressbyron


1 Answers

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.

like image 109
Krisztián Szabó Avatar answered Mar 16 '23 08:03

Krisztián Szabó