java 出現(xiàn)NullPointerException的原因及解決辦法
日常開(kāi)發(fā)過(guò)程中,最常見(jiàn)的異常莫過(guò)于NullPointerException,之前的時(shí)候,只是知道去找到報(bào)錯(cuò)的位置,然后去解決它,最近有空學(xué)習(xí)C語(yǔ)言,就去深究了下NullPointerException異常的本質(zhì)。
發(fā)生NullPointerException的情況:
首先,我們先找到Java.lang.NullPointerException這個(gè)類(lèi),內(nèi)容很簡(jiǎn)單:
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翻譯過(guò)來(lái)便是空指針,接下來(lái)我們首先要了解的是什么是指針,對(duì)于非C/C++的程序員來(lái)說(shuō),很多其它語(yǔ)言開(kāi)發(fā)者對(duì)指針的概念很模糊,說(shuō)白了,指針就是存儲(chǔ)變量的內(nèi)存地址,在c語(yǔ)言里面,NULL表示該指針不指向任何內(nèi)存單元,0表示指向地址為0的單元(這個(gè)單元一般是不能使用的)。先看一段C語(yǔ)言代碼:
void main() {  int* i = NULL;  printf("%#x/n", i);  printf("%#x/n", &i);  system("pause");}
在C語(yǔ)言里,你可以讀取NULL本身的值(void *)0,即0,但是讀取它指向的值,那是非法的,會(huì)引發(fā)段錯(cuò)誤。而Java里面的NULL就是直接指向了0,上述也說(shuō)了,指向地址為0的單元,一般是不能使用的。
一句話總結(jié):因?yàn)橹赶蛄瞬豢墒褂玫膬?nèi)存單元,虛擬機(jī)無(wú)法讀取它的值,最終導(dǎo)致NullPointerException。
如有疑問(wèn)請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
新聞熱點(diǎn)
疑難解答
圖片精選