Java報異常時getMessage()方法返回null


有次在查看項目日志的時候發現getMessage()返回值是null,以為是代碼寫的有問題,后來發現空指針異常時返回值就是null,雖然問題原因找到,但是感覺在日志中單單輸出null對我們查看日志不夠友好,想找到一種更好的方式。

原因

翻閱了API后發現getMessage()是Throwable類提供的方法

getMessage

public String getMessage()

Returns the detail message string of this throwable.

Returns:

the detail message string of this Throwable instance (which may be null).

 翻譯過來的意思大概是:返回當前拋出的Trowable實例的詳細信息(可能會是null)

從API中的說明可以得知,我們getMessage()得到的是null也不足為奇了,博主常遇見的null情況是空指針異常,具體是否還有其他的異常情況會得到null的也還不太清楚,看了其他博主的文章發現是會有其他異常也返回null的情況。

那么是否有更好的辦法可以讓我們知道輸出錯誤是什么呢,答案是肯定的,在經過一番查找后發現有以下兩種更好的方式:

  • 使用Exception的printStackTrace()方法
  • 使用Exception的toString()方法

區別

對比出現空指針異常時的區別

printStackTrace

當出現空指針異常時,會輸出異常類型和異常代碼所在的行數,在我們的代碼量多起來以后,會出現一個類調用另一個類,報異常時會將每個報錯的行都輸出,當調用關系復雜起來的時候會輸出一長串內容。

// 沒有其他類調用時

java.lang.NullPointerException
    at com.test.HelloWorld.main(HelloWorld.java:12)

// 其他類或方法調用時
java.lang.NullPointerException
    at com.test.HelloWorld.test(HelloWorld.java:11)
    at com.test.SecondTest.main(SecondTest.java:6)

toString

查看了jdk的源碼后發現NullPointerException本身沒有實現toString()函數,而是通過繼承使用Throwable的toString()函數,該函數會先獲取detailMessage的值(出現空指針異常時Throwable類的detailMessage為null,因此直接調用getMessage()方法會返回null),如果為空返回當前異常類名,否則返回detailMessage,所以即使是空指針異常也會返回java.lang.NullPointerException

/**
 * Returns a short description of this throwable.
 * The result is the concatenation of:
 * <ul>
 * <li> the {@linkplain Class#getName() name} of the class of this object
 * <li> ": " (a colon and a space)
 * <li> the result of invoking this object's {@link #getLocalizedMessage}
 *      method
 * </ul>
 * If {@code getLocalizedMessage} returns {@code null}, then just
 * the class name is returned.
 *
 * @return a string representation of this throwable.
 */
public String toString() {
    String s = getClass().getName();
    String message = getLocalizedMessage();
    return (message != null) ? (s + ": " + message) : s;
}

/**
 * Creates a localized description of this throwable.
 * Subclasses may override this method in order to produce a
 * locale-specific message.  For subclasses that do not override this
 * method, the default implementation returns the same result as
 * {@code getMessage()}.
 *
 * @return  The localized description of this throwable.
 * @since   JDK1.1
 */
public String getLocalizedMessage() {
    return getMessage();
}

/**
 * Returns the detail message string of this throwable.
 *
 * @return  the detail message string of this {@code Throwable} instance
 *          (which may be {@code null}).
 */
public String getMessage() {
    return detailMessage;
}

結論

僅需要知道返回的異常類型時使用Exception的toString()方法,需要知道報錯詳情則使用Exception的printStackTrace()方法。

才疏學淺,如文中有錯誤,感謝大家指出。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM