[java] Catching nullpointerexception in Java

I tried using try-catch block to catch NullPointerException but still the following program is giving errors. Am I doing something wrong or is there any other way to catch NullPointerException in the following program. Any help is highly appreciated.

public class Circular_or_not 
{

    /**
     * @param args
     */
    public static void main(String[] args) 
    {
        // TODO Auto-generated method stub
        try
        {
            LinkedListNode[] nodes = new LinkedListNode[10];            
            for (int i = 0; i < 10; i++) 
            {
                nodes[i] = new LinkedListNode(i, null, i > 0 ? nodes[i - 1] : null);
            }

            // Create loop;
            // nodes[9].next = nodes[3];
            Boolean abc= Check_Circular(nodes[0]);
            System.out.print(abc);
        }
        catch(NullPointerException e)
        {
            System.out.print("NullPointerException caught");
        }

    }

    public static boolean Check_Circular(LinkedListNode head) 
    {       
            LinkedListNode n1 = head;
            LinkedListNode n2 = head; 

            // Find meeting point
            while (n2.next != null)
            { 
                n1 = n1.next; 
                n2 = n2.next.next; 
                if (n1 == n2) 
                { 
                    return true;
                }
            }
            return false;
    }

}

This question is related to java nullpointerexception

The answer is


As stated already within another answer it is not recommended to catch a NullPointerException. However you definitely could catch it, like the following example shows.

public class Testclass{

    public static void main(String[] args) {
        try {
            doSomething();
        } catch (NullPointerException e) {
            System.out.print("Caught the NullPointerException");
        }
    }

    public static void doSomething() {
        String nullString = null;
        nullString.endsWith("test");
    }
}

Although a NPE can be caught you definitely shouldn't do that but fix the initial issue, which is the Check_Circular method.


The problem with your code is in your loop in Check_Circular. You are advancing through the list using n1 by going one node at a time. By reassigning n2 to n2.next.next you are advancing through it two at a time.

When you do that, n2.next.next may be null, so n2 will be null after the assignment. When the loop repeats and it checks if n2.next is not null, it throws the NPE because it can't get to next since n2 is already null.

You want to do something like what Alex posted instead.


I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException


You should be catching NullPointerException with the code above, but that doesn't change the fact that your Check_Circular is wrong. If you fix Check_Circular, your code won't throw NullPointerException in the first place, and work as intended.

Try:

public static boolean Check_Circular(LinkedListNode head)
{
    LinkedListNode curNode = head;
    do
    {
        curNode = curNode.next;
        if(curNode == head)
            return true;
    }
    while(curNode != null);

    return false;
}

NullPointerException is a run-time exception which is not recommended to catch it, but instead avoid it:

if(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}