Scala program to demonstrate the NullPointerException

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

Scala - NullPointerException Example

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

Scala code to demonstrate the NullPointerException

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

// Scala program to demonstrate the
// NullPointerException

object Sample {
  // Main method
  def main(args: Array[String]) {
    val str: String = null
    try {
      // Generate NullPointerException
      println("Length of string: " + str.length);
    } catch {
      case e: NullPointerException => println(e);
    }
  }
}

Output

java.lang.NullPointerException

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 a string variable str initialized with null. Then we tried to find the length of the string in the try block. That's why NullPointerException 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 www.includehelp.com. All rights reserved.