虚位以待(AD)
虚位以待(AD)
首页 > 软件编程 > C/C++编程 > java 出现NullPointerException的原因及解决办法

java 出现NullPointerException的原因及解决办法
类别:C/C++编程   作者:码皇   来源:互联网   点击:

这篇文章主要介绍了java 出现NullPointerException的原因及解决办法的相关资料,这里说明出现NullPointerException 的原因的总结,并说明该如何解决,需要的朋友可以参考下

java 出现NullPointerException的原因及解决办法

日常开发过程中,最常见的异常莫过于NullPointerException,之前的时候,只是知道去找到报错的位置,然后去解决它,最近有空学习C语言,就去深究了下NullPointerException异常的本质。

发生NullPointerException的情况:

  • 调用 null 对象的实例方法。
  • 访问或修改 null 对象的字段。
  • 如果一个数组为null,试图用属性length获得其长度时。
  • 如果一个数组为null,试图访问或修改其中某个元素时。
  • 在需要抛出一个异常对象,而该对象为 null 时。

首先,我们先找到Java.lang.NullPointerException这个类,内容很简单:

    package java.lang;
    /** * Thrown when a program tries to access a field or method of an object or an * element of an array when there is no instance or array to use, that is if the * object or array points to {
    @code null}
    . It also occurs in some other, less * obvious circumstances, like a {
    @code throw e}
    statement where the {
    @link * Throwable}
    reference is {
    @code null}
    . */public class NullPointerException extends RuntimeException {
    private static final long serialVersionUID = 5162710183389028792L;
    /** * Constructs a new {
    @code NullPointerException}
    that includes the current * stack trace. */ public NullPointerException() {
    }
    /** * Constructs a new {
    @code NullPointerException}
    with the current stack * trace and the specified detail message. * * @param detailMessage * the detail message for this exception. */ public NullPointerException(String detailMessage) {
    super(detailMessage);
    }
    }

NullPointerException翻译过来便是空指针,接下来我们首先要了解的是什么是指针,对于非C/C++的程序员来说,很多其它语言开发者对指针的概念很模糊,说白了,指针就是存储变量的内存地址,在c语言里面,NULL表示该指针不指向任何内存单元,0表示指向地址为0的单元(这个单元一般是不能使用的)。先看一段C语言代码:

    void main() {
    int* i = NULL;
    printf("%#xn", i);
    printf("%#xn", &i);
    system("pause");
    }

在C语言里,你可以读取NULL本身的值(void *)0,即0,但是读取它指向的值,那是非法的,会引发段错误。而Java里面的NULL就是直接指向了0,上述也说了,指向地址为0的单元,一般是不能使用的。

一句话总结:因为指向了不可使用的内存单元,虚拟机无法读取它的值,最终导致NullPointerException。

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

相关热词搜索: java NullPointerException java NullPoin