欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java 出現(xiàn)NullPointerException的原因及解決辦法

 更新時間:2017年08月29日 15:48:13   投稿:lqh  
這篇文章主要介紹了java 出現(xiàn)NullPointerException的原因及解決辦法的相關資料,這里說明出現(xiàn)NullPointerException 的原因的總結,并說明該如何解決,需要的朋友可以參考下

java 出現(xiàn)NullPointerException的原因及解決辦法

日常開發(fā)過程中,最常見的異常莫過于NullPointerException,之前的時候,只是知道去找到報錯的位置,然后去解決它,最近有空學習C語言,就去深究了下NullPointerException異常的本質。

發(fā)生NullPointerException的情況:

  • 調用 null 對象的實例方法。
  • 訪問或修改 null 對象的字段。
  • 如果一個數(shù)組為null,試圖用屬性length獲得其長度時。
  • 如果一個數(shù)組為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);
  }

}

NullPointerException翻譯過來便是空指針,接下來我們首先要了解的是什么是指針,對于非C/C++的程序員來說,很多其它語言開發(fā)者對指針的概念很模糊,說白了,指針就是存儲變量的內存地址,在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,但是讀取它指向的值,那是非法的,會引發(fā)段錯誤。而Java里面的NULL就是直接指向了0,上述也說了,指向地址為0的單元,一般是不能使用的。

一句話總結:因為指向了不可使用的內存單元,虛擬機無法讀取它的值,最終導致NullPointerException。

如有疑問請留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關文章

最新評論