Scala program to demonstrate the NumberFormatException

Here, we are going to demonstrate the NumberFormatException in Scala programming language.
Submitted by Nidhi, on June 08, 2021 [Last updated : March 12, 2023]

Scala - NumberFormatException Example

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

Scala code to demonstrate the NumberFormatException

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);


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


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.

Scala Exception Handling Programs »

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.