Java 核心 Exception 和 Error 有什麼區別?

問題

Exception 和 Error 有什麼區別?運行時異常與通常異常有什麼區別?java

解析

Exception 和 Error 都繼承了 Throwable 類。只有 Throwable 的能夠被 throw 和 catch。Exception 是程序正常狀況下能夠預料的,Error 一般會致使程序不可恢復。Exception 分爲可檢查異常和不檢查異常,不檢查異常就是運行時異常。
在這裏插入圖片描述編程

NoClassDefFoundError 和 ClassNotFoundException 區別

NoClassDefFoundError 一般發生在打包錯誤致使編譯時找獲得包而運行時找不到包致使的項目不能啓動的錯誤,ClassNotFoundException 發生在好比用 Class.fromName() 加載一個不存在的包致使的 Exception。學習

異常處理的基本原則

  1. 捕獲特定異常
  2. 不要 swallow 異常

例如:ui

try {
 // 業務代碼
 // …
 Thread.sleep(1000L);
} catch (Exception e) {
 // Ignore it
}

Throw early, catch late 原則

  1. 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...
}
  1. catch late

可考慮使用自定義異常,方便定位,同時注意不要暴漏敏感信息。如用戶信息不容許輸出。spa

(想自學習編程的小夥伴請搜索圈T社區,更多行業相關資訊更有行業相關免費視頻教程。徹底免費哦!)3d

相關文章
相關標籤/搜索