Java 核心 Exception 和 Error 有什麼區別?
阿新 • • 發佈:2019-12-31
問題
Exception 和 Error 有什麼區別?執行時異常與一般異常有什麼區別?
解析
Exception 和 Error 都繼承了 Throwable 類。只有 Throwable 的可以被 throw 和 catch。Exception 是程式正常情況下可以預料的,Error 通常會導致程式不可恢復。Exception 分為可檢查異常和不檢查異常,不檢查異常就是執行時異常。
NoClassDefFoundError 和 ClassNotFoundException 區別
NoClassDefFoundError 通常發生在打包錯誤導致編譯時找得到包而執行時找不到包導致的專案不能啟動的錯誤,ClassNotFoundException 發生在比如用 Class.fromName() 載入一個不存在的包導致的 Exception。
異常處理的基本原則
- 捕獲特定異常
- 不要 swallow 異常
例如:
try {
// 業務程式碼
// …
Thread.sleep(1000L);
} catch (Exception e) {
// Ignore it
}
複製程式碼
Throw early,catch late 原則
- throw early
public void readPreferences(String fileName){
//...perform operations...
InputStream in = new FileInputStream(fileName);
//...read the preferences file...
}
public void readPreferences(String filename) {
Objects. requireNonNull(filename);
//...perform other operations...
InputStream in = new FileInputStream(filename);
//...read the preferences file...
}
複製程式碼
- catch late
可考慮使用自定義異常,方便定位,同時注意不要暴漏敏感資訊。如使用者資訊不允許輸出。
每一次成長,都想與你分享。