Examples of Exceptions


🙋 Need help? Ask an expert now!

Let's move on to another common error many programmers have experienced first-hand, the "NullPointerException". Remember that a null value can be assigned to any object reference including strings. The NullPointerException is thrown when the program tries to use an object reference that has the null value. Take a look below to see an example.
package exlcode;

public class NullPointerExample {

  public static void main(String[] args) {
    try {
      // NullPointerException will be thrown because
      // exampleVariableOne is being compared to a null value
      Double exampleVariableOne = new Double(Math.PI);
      Double exampleVariableTwo = null;
      System.out.println("None of the objects are null");
    } catch (NullPointerException e) {
      System.out.println("exampleVariableOne cannot be compared to a null value");

The "NullPointerException" is thrown when we compare an object to a null value. As an exercise, change the value above to stop the exception from being thrown.

Working with null values may not be the best practice because there may be situations where the "NullPointerException" is thrown by the program. The most effective way to avoid a "NullPointerException" is to check all object references before accessing one of the object's fields or methods. Use the try{} and catch{} blocks to check if the object is null.

Edit Me on GitHub!

Application Question

Which of the following throws a NullPointerException?