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("%#x/n", i); printf("%#x/n", &i); system("pause");}
在C語言里,你可以讀取NULL本身的值(void *)0,即0,但是讀取它指向的值,那是非法的,會引發段錯誤。而Java里面的NULL就是直接指向了0,上述也說了,指向地址為0的單元,一般是不能使用的。
一句話總結:因為指向了不可使用的內存單元,虛擬機無法讀取它的值,最終導致NullPointerException。
如有疑問請留言或者到本站社區交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選