[CLJ-1332] Exceptions are not cached in lazy seqs Created: 29/Jan/14 Updated: 13/Feb/14
It is confusing that exceptions will only be thrown once when it is possible to iterate over a seq many times.
user=> (def a (for [i (reverse (range 2))] (/ 1 i)))
ArithmeticException Divide by zero clojure.lang.Numbers.divide
|Comment by Gary Fredericks [ 13/Feb/14 10:29 PM ]|
The cause of this is the lazy-seq macro which uses :once metadata to signal to the compiler that the thunk it creates will only be called once.
When the evaluation of a lazy seq throws an exception, trying to walk the seq again causes the function to be called a second time. Since its closed over values have likely been cleared by that point, you get different behavior.
Glancing at LazySeq.java made me pretty convinced you can't cache exceptions without adding an extra check somewhere in the standard codepath for lazy seq traversal.
|Comment by Yongqian Li [ 13/Feb/14 11:38 PM ]|
Btw, I ran into this issue while trying to evaluate a lazy-seq in a future in order to do some processing concurrently in the background. Any suggestions for workarounds?