How to handle NullPointerException?

QuestionsQuestions8 SkillsProJava Exception HandlingNov, 13 2025
0121

To handle a NullPointerException in Java, you can use a try-catch block. Here’s a basic example:

public class NullPointerExample {
    public static void main(String[] args) {
        String str = null;
        try {
            // Attempt to access a method on a null object
            int length = str.length(); // This will throw NullPointerException
            System.out.println("Length: " + length);
        } catch (NullPointerException e) {
            // Handle the exception
            System.out.println("Error: " + e.getMessage() + " - String is null.");
        }
    }
}

Steps to Handle NullPointerException:

  1. Wrap the Code: Place the code that might throw a NullPointerException inside a try block.

  2. Catch the Exception: Use a catch block to catch the NullPointerException.

  3. Handle the Exception: Inside the catch block, you can log the error, display a message, or take corrective actions.

Best Practices:

  • Check for Null: Before accessing an object, check if it is null to prevent the exception.

    if (str != null) {
        int length = str.length();
        System.out.println("Length: " + length);
    } else {
        System.out.println("String is null.");
    }
  • Use Optional: In Java 8 and later, consider using Optional to avoid null references.

By following these practices, you can effectively handle NullPointerException and improve the robustness of your code.

0 Comments

no data
Be the first to share your comment!