I am very curious as to why the exception is thrown in the following foreach
block. I would expect that no values make it past the filter and thus the foreach
block is never reached. The same behavior occurs with map
.
scala> (1 to 10) filter { _ > 12 } foreach { throw new Exception }
java.lang.Exception
... 33 elided
I would expect the exception to not to be thrown and behave more like the following where println
is never executed.
scala> (1 to 10) filter { _ > 12 } foreach { println _ }
Maybe this has to do with how exceptions are handled? Why is this?
{ throw new Exception }
is just a block which throws an exception - as a result it has type Nothing
. Since Nothing
is a subtype of all types, it is compatible with Function[Int, T]
which is required as the argument to the foreach
block.
You can see this more clearly if you create the function beforehand:
//throws exception
val f: Function[Int, Unit] = { throw new Exception }
If you want to create a Function[Int, Nothing]
you need to add the parameter to the block:
(1 to 10) filter { _ > 12 } foreach { _ => throw new Exception }
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