Saturday, October 24, 2015

Exception-throwing is neither reference transparent nor type safe

Replacing y in places where it’s used should produce the same result, but it doesn’t:

object Example {
  def failingFn: Int = {
    val y: Int = throw new Exception("fail!")
    try {
      val x = 42 + 5
      x + y
    }
    catch {case e: Exception => 445}
  }
  def failingFn2: Int = {
    try {
      val x = 42 + 5
      x + ((throw new Exception("fail!")): Int)
    }
    catch {case e: Exception => 445}
  }
}


object Test {

  import Example._
  failingFn  // error
  failingFn2 // 445
}

0 comments: