在 Java 中捕获空指针异常 [英] Catching nullpointerexception in Java

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

问题描述

我尝试使用 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(someVariable != null) someVariable.doSomething();
else
{
    // do something else
}

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆