好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

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

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

发生NullPointerException的情况:

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

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

?

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

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语言代码:

?

1

2

3

4

5

6

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。

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

原文链接:http://blog.csdn.net/pangpang123654/article/details/52370669

查看更多关于java 出现NullPointerException的原因及解决办法的详细内容...

  阅读:36次