java 出现NullPointerException的原因及解决办法
|
java 出现NullPointerException的原因及解决办法 日常开发过程中,最常见的异常莫过于NullPointerException,之前的时候,只是知道去找到报错的位置,然后去解决它,最近有空学习C语言,就去深究了下NullPointerException异常的本质。 发生NullPointerException的情况:
首先,我们先找到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。 如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持! (编辑:南平站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |



