Java異常類層次結(jié)構(gòu)
+-----------+
| Throwable |
+-----------+
/ \
/ \
+-------+ +-----------+
| Error | | Exception |
+-------+ +-----------+
/ | \ / | \
\________/ \______/ \
+------------------+
unchecked checked | RuntimeException |
+------------------+
/ | | \
\_________________/
unchecked
- Error:一般是指與虛擬機(jī)相關(guān)的問(wèn)題,如系統(tǒng)崩潰,虛擬機(jī)錯(cuò)誤,內(nèi)存空間不足,方法調(diào)用棧溢出等。如
java.lang.StackOverFlowError和Java.lang.OutOfMemoryError。對(duì)于這類錯(cuò)誤,Java編譯器不去檢查他們。對(duì)于這類錯(cuò)誤的導(dǎo)致的應(yīng)用程序中斷,僅靠程序本身無(wú)法恢復(fù)和預(yù)防,遇到這樣的錯(cuò)誤,建議讓程序終止。 - Exception:表示程序可以處理的異常,可以捕獲且可能恢復(fù)。遇到這類異常,應(yīng)該盡可能處理異常,使程序恢復(fù)運(yùn)行,而不應(yīng)該隨意終止異常。
常見(jiàn)的異常:
- OutOfMemoryError:VirtualMachineError的子類,VirtualMachineError是Error的子類;
- StackOverflowError:同上;
- IOException:Exception的子類,屬于checked exception。常見(jiàn)的子類有FileNotFoundException等。而IOError則是Error的子類;
- RunTimeException:運(yùn)行時(shí)異常,屬于unchecked exception,其常見(jiàn)的子類有NullPointerException等
checked/unchecked Exception分類
- unchecked exception:run-time exception + error;
- checked exception:除了unchecked exception的其他所有異常,即除了RunTimeException及其子類、Error及其子類的所有Throwable的子類。
oracle英文原文見(jiàn)參考資料4。
兩者的區(qū)別:
- checked exception:必須在代碼中處理該Exception,否則會(huì)編譯不通過(guò)??梢酝ㄟ^(guò)try-catch或throws讓調(diào)用者處理;
- unchecked exception:可能是代碼邏輯錯(cuò)誤引起的,但不處理也能編譯通過(guò)
throw、throws
- throw用在方法體內(nèi),是具體向外拋異常的動(dòng)作,表示既定事實(shí),如
throw new Exception("error."); - throws用在函數(shù)聲明中,表明該函數(shù)可能拋出某種類型的異常,需要調(diào)用者處理,表示傾向,如
public void test() throws IOException。
try-catch-finally、try with resources
// before Java 7:
try {
// open resources like File, Database connection, Sockets etc
} catch (FileNotFoundException e) {
// Exception handling like FileNotFoundException, IOException etc
} finally{
// close resources
}
// Java 7 try with resources implementation:
try(// open resources here){
// use resources
} catch (FileNotFoundException e) {
// exception handling
}
// resources are closed as soon as try-catch block is executed.
Java 7之前必須顯示的關(guān)閉,否則會(huì)導(dǎo)致內(nèi)存泄漏
Java try with resources 的好處:
- 代碼的可讀性更好,更易于編寫(xiě)代碼
- 自動(dòng)化的資源管理
- 代碼的行數(shù)被減少
- 不需要使用finally塊來(lái)關(guān)閉資源
- 可在try-with-resources中使用分號(hào)來(lái)間隔多個(gè)資源,會(huì)在關(guān)閉時(shí)通過(guò)逆序的方式關(guān)閉
任何資源在用于 try-with-resources 時(shí),都需要實(shí)現(xiàn) java.lang.AutoCloseable,否則Java編譯器會(huì)拋出編譯問(wèn)題
異常的日志打印
- e:獲取的信息包括異常類型和異常詳細(xì)消息
- e.getMessage:只會(huì)獲得具體的異常名稱. 比如說(shuō)NullPoint 空指針,就告訴你說(shuō)是空指針
- e.printStackTrace:會(huì)打出詳細(xì)異常,異常名稱,出錯(cuò)位置,便于調(diào)試用...一般一個(gè)異常至少幾十行
在使用slf4j打印異常時(shí),不需要占位符,只需這么打?。?code>logger.error("error = ", e);,下面這種是錯(cuò)誤的:logger.error("error = {}", e);