異常
1
異常類的層次結構使用總結:
2 補充
- 常見RuntimeException有,錯誤類型轉換,數組訪問越界,訪問null指針。
- 使用包裝技術,不丟失原始異常細節。當需要把捕獲的原始異常設置爲新的異常時,使用包裝技術不會丟失原始異常細節。 .initCause(e)將原始異常進行包裝;.getCause()獲取原始異常類型。(底層框架對原始異常捕獲,進行包裝拋出新的異常。你不能更改框架,當需要獲取原始異常時,getCause()就很有用)
/**
* 包裝異常,獲取原始異常示例
* @author gao tianci
* @version $Id: TestException.java, v 0.1 2017年7月18日 下午9:58:43 gao tianci Exp $
*/
public class TestException {
@Test
public void test() {
try {
throwIllegealOne();
} catch (IllegalArgumentException e) {
System.out.println("------(initCause())------");
System.out.println(e.getMessage());
System.out.println(e.getCause() instanceof SQLException);
}
try {
throwIllegealTwo();
} catch (IllegalArgumentException e) {
System.out.println("-----------(e)-----------");
System.out.println(e.getMessage());
System.out.println(e.getCause() instanceof SQLException);
}
try {
throwIllegealThree();
} catch (IllegalArgumentException e) {
System.out.println("---------(msg+e)---------");
System.out.println(e.getMessage());
System.out.println(e.getCause() instanceof SQLException);
}
}
//SQLException
public static void throwSQL() throws SQLException {
throw new SQLException("sql error.");
}
//initCause()
public static void throwIllegealOne() throws IllegalArgumentException {
try {
throwSQL();
} catch (SQLException e) {
IllegalArgumentException illegal = new IllegalArgumentException("參數非法");
illegal.initCause(e);
throw illegal;
}
}
//e
public static void throwIllegealTwo() throws IllegalArgumentException {
try {
throwSQL();
} catch (SQLException e) {
throw new IllegalArgumentException(e);
}
}
//msg + e
public static void throwIllegealThree() throws IllegalArgumentException {
try {
throwSQL();
} catch (SQLException e) {
throw new IllegalArgumentException("參數非法" + e);
}
}
}
測試結果:
------(initCause())------
參數非法
true
-----------(e)-----------
java.sql.SQLException: sql error.
true
---------(msg+e)---------
參數非法java.sql.SQLException: sql error.
false
-
分析堆棧軌跡
堆棧軌跡是一個方法調用過程的列表。可藉助Throwable類的printStackTrace()或getStackTrace()方法進行分析。靜態的Thread.getAllStackTrace()方法,它可以產生所有線程的堆棧軌跡。 -
踩過的坑
一個方法的內部開啓了多線程處理,多線程裏出現了異常,你在方法出口處肯定捕捉不到!因爲他們不是一個線程了!!!
斷言
- 斷言,斷言機制允許在測試期間向代碼插入一些檢查語句,當代嗎發佈時,這些插入的檢查語句會被自動地移走。
- 兩種形式:assert 條件;assert 條件:表達式;
都會對條件進行檢測,第一種情況,條件爲false,拋出AssertionError異常,第二種,把表達式傳給AssertionError的構造器。 - 默認情況下,斷言禁用,可以開啓包級別的斷言;也可開啓系統級別的斷言。
- 工作中尚未見到使用很多斷言,自測的時候可以輔助使用一些。
##日誌 ##
java自帶的日誌包在 java.util.logging.*中。使用開源的日誌組件會更友好,強烈推薦slf4j,代碼簡潔,格式化方便。
eg:
logger.info("Processing trade with id: {} and symbol : {} ", id, symbol);
此外常用的還有,log4j;logback等組件。