Try catch of iterator transformation

scala

a common mistake I never thought I will make

Check below code, I have thought the exception should be caught by the surrounding try catch block but it doesn’t.

def f(iter: Iterator[Int]): Iterator[Int] = {
    try {
      iter.map { a =>
        throw new Exception("failed")
      }
    } catch {
      case ex: Exception =>
        Iterator.empty
    }
  }

def main(args: Array[String]): Unit = {
	// exception thrown
	f(Seq(1, 2, 3).toIterator).toList
}

An exception is raised in main. This is due to iterator transformation merely produces a new iterator without performing any real transformations. Only when certain actions are applied to the iterator, the transformation starts to initiate. When f is called, a new iterator is returned which wraps the logic in the next() method. The mapping logic is truly executed once calling the action toList.

4f0f7cbf-e8c4-4a7e-bdf9-14df185aa01d