【Exceptipn(一)】unchecked Exception 與 checked Exception

目錄

背景

概念

checked Exception

unchecked Exception

使用

參考


背景

最近在讀《代碼精進之路 從碼農到工匠》,在異常規範中有講到,建議使用unchecked Exception,而不是checked Exception。名詞看着很眼熟,完全忘記了含義,於是就查了查,以做記錄。

概念

checked Exception

繼承自Error,在開發中是必須顯式處理的異常,對於會拋出該異常的方法,調用方必須用try catch捕獲該異常進行處理或者在方法簽名上throws 該異常,向上傳播。例如 FileNotFoundException。

unchecked Exception

繼承自Runtime Exception,非必須顯式處理的異常,可以在開發過程中自行避免,如 Null Point Exception。

使用

個人看法,自定義異常,建議使用unchecked Exception,可以使代碼簡潔。大佬在書中也是這樣建議的。orz

參考

檢查型異常(Checked Exception)與非檢查型異常(Unchecked Exception)

checked Exception和unchecked Exception的區別

checked exception和unchecked exception的區別

Java異常:選擇Checked Exception還是Unchecked Exception?

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章