在Java中捕获nullpointerexception

在Java中捕获nullpointerexception

本文介绍了在Java中捕获nullpointerexception的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用try-catch块来捕获 NullPointerException ,但仍然是以下程序出错。我做错了什么或者在以下程序中有没有其他方法来捕获 NullPointerException 。任何帮助都非常感谢。

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 是一个运行时异常,不建议捕获它,而是避免它:

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

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

这篇关于在Java中捕获nullpointerexception的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 00:20