Helpful NullPointerExceptions

Quick summary:

  • Provides more descriptive error messages for NullPointerExceptions, indicating exactly which variable or operation was null.
  • Released in Java 14 (2020).

Key Features

  • Detailed Error Messages: Error messages now indicate the specific variable or field that was null, making it easier to identify the source of the problem.
  • Reduced Debugging Time: The enhanced details help developers quickly understand what caused the exception, significantly cutting down debugging time.
  • Automatic Enhancement: No changes to existing code are needed to benefit from more informative null pointer exceptions.

Example

Before Java 17:

Before, whenever you accidentally caused a null pointer exception, you wouldn’t get many clues as to exactly where it happened.

    String firstName = "James";
    String lastName = null;

    if (firstName.length() + lastName.length() < 10) {
        System.out.println("Your name is super short!");
    }

In earlier Java versions, this would throw a generic NullPointerException without indicating that lastName is null.

After Java 17:

Now, the exception message would include “Cannot invoke “String.length()” because “lastName” is null”, pointing directly to the null reference.

    String firstName = "James";
    String lastName = null;

    if (firstName.length() + lastName.length() < 10) {
        System.out.println("Your name is super short!");
    }

👩‍💻 Hands-on Demo: Helpful NullPointerExceptions

  1. Copy the following code for the Person-class and PersonApp-class.
public class Person {
    private String fullName;
    private List<String> hobbies;

    public Person(String fullName) {
        this.fullName = fullName;
    }

    public String getFullName() {
        return fullName;
    }

    public void setFullName(String fullName) {
        this.fullName = fullName;
    }

    public List<String> getHobbies() {
        return hobbies;
    }

    public void setHobbies(List<String> hobbies) {
        this.hobbies = hobbies;
    }

    public void addHobby(String hobby) {
        hobbies.add(hobby);
    }
}
public class PersonApp {
    public static void main(String[] args) {
        Person person = new Person("James Barnes");
        person.addHobby("reading");
        person.addHobby("sleeping");
        System.out.printf("%s's hobbies are: %s\n", person.getFullName(), person.getHobbies());
    }
}
  1. Run the code and experience the null pointer exception.
  2. Use the helpful null pointer exception to locate and debug the issue.
  3. Rerun your code after debugging to confirm it works.

Solutions

🕵️‍♂️ Click here to reveal the solutions
    public void addHobby(String hobby) {
        if (hobbies == null) {
            hobbies = new ArrayList<>();
        }
        hobbies.add(hobby);
    }