Try/catch does not compile

I would like to know why the following code does not compile

try {
     val n = args(0).toInt
     } catch {
      case e: NumberFormatException => {println("Wrong number")
        val n = 0}
     }

    println(n)
// error: not found: value n

My first idea was that NumberFormatException is not all bad what can happen. Then I replaced it with

case e: Throwable => {println("Anything wrong"); val n = 0}

but the effect is the same.

The variable n defined inside the try is not available after the closing curly brace. The same is for the other n-variable defined inside catch.

The problem can be solved by introducing the variable in the same scope as the println -statement that uses it

val n = try { 
    args(0).toInt
  } catch {
    case e: NumberFormatException => {
       println("Wrong number")
       0
    }
}

println(n)
3 Likes

Ok, I see. But what if I do not want to return anything in the case of exception, just exit after printing?

Well, it depends on where you need the value. You could of course move the normal print inside the try.

try { 
    val n = args(0).toInt
    println(n)
  } catch {
    case e: NumberFormatException => {
       println("Wrong number")
    }
}

Note also that since 2.13 you can also use toIntOption() which gives you an Option[Int] without a need for a try-catch

2 Likes