C Sharp

What is a NullPointerException (NPE)?

Overview

A NullPointerException is an exception that is thrown when you try to reference an object or a method that does not exist in memory.

Here is an example on how a NPE gets thrown:

public class NullPointerExceptionExample {

    public static void main(String[] args) {

        tesla.start();

        // this code will throw an NPE as "tesla" is not defined. And since we are trying to call method start() on an object which is null, the exception will be thrown.
    }

}

A NullPointerException can also occur if you have a method that simply assumes that the input object is never null. Here is an example:



public class NullPointerExceptionExample {

    public string ThisCanNeverBeNull (Object tesla) {

        tesla.start();

/*
This code will throw an NPE if the input to the method "tesla" is null. And since we are trying to call method start() on an object which is null, the exception will be thrown.

Alternatively, this code can also throw an NPE if "tesla" is defined but the method start() is not defined for the tesla object.

*/

    }

}

How to avoid NullPointerException (NPE)?

Ideally, if you get an NPE either you need to put a boundary condition around the code where the exception is occurring and check for null before referencing the object causing NullPointerException.

Alternatively, you can also wrap that code in a try/catch block and catch the NPE and log it appropriately while doing the best thing in the catch block depending on the use case of your code. In most cases, you want to just catch it, log it and raise an alert for it so that you can improve the reliability of your application and fix it.

Leave a Reply