这篇文章主要为大家展示了“java中出现NullPointerException的原因是什么”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“java中出现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("%#x\n", i);
printf("%#x\n", &i);
system("pause");
}
在C语言里,你可以读取NULL本身的值(void *)0,即0,但是读取它指向的值,那是非法的,会引发段错误。而Java里面的NULL就是直接指向了0,上述也说了,指向地址为0的单元,一般是不能使用的。
一句话总结:因为指向了不可使用的内存单元,虚拟机无法读取它的值,最终导致NullPointerException。
以上是“java中出现NullPointerException的原因是什么”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。