List of Topics:
Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Handle NullPointerException in Java?

Handle NullPointerException in Java

Condition for Handling NullPointerException in Java

  • Description: A NullPointerException occurs when accessing methods or fields on a null object. It can be handled using a try-catch block, checking for null values before use, and ensuring proper initialization to avoid crashes. In the try-catch block, you attempt to perform operations that may result in a null pointer access, and in the catch block, you handle the exception by logging an appropriate message. Additionally, always ensure objects are properly initialized before use to avoid the occurrence of this exception.
Sample Source Code
  • # NullPointerException.java
    package JavaSamples2;

    public class NullPointerException {
    public static void main(String args[]){
    String str = null;

    try {
    System.out.println(str.length()); // Attempting to access method on null
    } catch (Exception e) {
    System.out.println("Error: Null pointer encountered. Please check your object initialization.");
    } finally {
    System.out.println("Execution complete.");
    }
    }
    }
Screenshots
  • STEP 1: The NullPointerException will be displayed in the output window.
  • The NullPointerException will be displayed in the output window.

Related Links