什么是空指针异常

来源:互联网 发布:淘宝好评返现处罚条例 编辑:程序博客网 时间:2024/05/17 17:18

日常开发过程中,最常见的异常莫过于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);    }}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32

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

void main() {    int* i = NULL;    printf("%#x\n", i);    printf("%#x\n", &i);    system("pause");}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

null

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

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

http://blog.csdn.net/pangpang123654/article/details/52370669

原创粉丝点击