目錄
背景
最近在讀《代碼精進之路 從碼農到工匠》,在異常規範中有講到,建議使用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的區別