Q:

Scala program to demonstrate the NumberFormatException

belongs to collection: Scala Exception Handling Programs

0

Here, we will demonstrate NumberFormatException using the try and catch blocks.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Program/Source Code:

The source code to demonstrate the NumberFormatException is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to demonstrate the
// NumberFormatException

object Sample {
  // Main method
  def main(args: Array[String]) {
    var num: Int = 0;
    try {
      num = "Hello".toInt;
    } catch {
      case e: NumberFormatException => println(e);
    }
  }
}

Output:

java.lang.NumberFormatException: For input string: "Hello"

Explanation:

In the above program, we used an object-oriented approach to create the program.

And, we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we created an integer variable num initialized with 0. Then we tried to convert the "Hello" string into a number in the try block. That's why NumberFormatException gets generated that will be caught in the catch block and print an appropriate message on the console screen.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Scala program to demonstrate the NullPointerExcept... >>
<< Scala program to create a custom exception...