如何在Java中避免null 指標異常

來源:互聯網
上載者:User

null 指標異常(Null Pointer Exception)是我們平時最容易碰到的,也是最令人討厭的異常。本文介紹如何避免出現null 指標異常。

首先我們看如下的樣本

private Boolean isFinished(String status) {       if (status.equalsIgnoreCase("Finish")) {         return Boolean.TRUE;       } else {         return Boolean.FALSE;       }     }

如果status的值為空白的話,那麼將會出現null 指標異常(本例第2行)。所以我們應該使用如下的方法

private Boolean isFinished(String status) {        if ("Finish".equalsIgnoreCase(status)) {            return Boolean.TRUE;        } else {            return Boolean.FALSE;        }    }

這樣的話,如果status為空白,也不會出現null 指標異常。相信我們大多數朋友已經知道這樣的方法了,如果一個對象可能為null,那麼不需要直接調用它的方法。

接下來我將接著提供幾種避免null 指標的建議。

1.判斷Collection是否為空白。

2.使用一些判斷方法。

3.assert關鍵字。

4.Assert類。

5.異常處理。

6.太多的點.操作文法。

7.使用StringUtils類

1.判斷Collection是否為空白

Collection 為空白是指Collection中沒有元素。一些開發人員如果碰到Collection中沒有元素的時候,經常return null,更好的做法是,你應該return Collections.EMPTY_LIST,Collections.EMPTY_SET或者是Collections.EMPTY_MAP.

錯誤的代碼

public static List getEmployees() {     List list = null;     return list;   }

正確的代碼

public static List getEmployees() {    List list = Collections.EMPTY_LIST;    return list;  }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.