Nick Allen
Nick Allen

Reputation: 1467

Throwing Exception in Foreach/Map Block

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?

Upvotes: 9

Views: 2085

Answers (1)

Lee
Lee

Reputation: 144136

{ 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 }

Upvotes: 7

Related Questions