Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Throwing Exception in Foreach/Map Block

Tags:

scala

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?

like image 373
Nick Allen Avatar asked May 14 '15 12:05

Nick Allen


1 Answers

{ 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 }
like image 110
Lee Avatar answered Oct 05 '22 08:10

Lee