java 出現NullPointerException的原因及解決辦法
日常開發(fā)過程中,最常見的異常莫過于NullPointerException,之前的時候,只是知道去找到報錯的位置,然后去解決它,最近有空學習C語言,就去深究了下NullPointerException異常的本質。
發(fā)生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++的程序員來說,很多其它語言開發(fā)者對指針的概念很模糊,說白了,指針就是存儲變量的內存地址,在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,但是讀取它指向的值,那是非法的,會引發(fā)段錯誤。而Java里面的NULL就是直接指向了0,上述也說了,指向地址為0的單元,一般是不能使用的。
一句話總結:因為指向了不可使用的內存單元,虛擬機無法讀取它的值,最終導致NullPointerException。
如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/pangpang123654/article/details/52370669