Catching nullpointerexception in Java [closed]

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;
    }

}

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
}

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.