Java異常有checked exception(受檢異常)和unchecked exception(不受檢異常), 編譯器在編譯時,對於受檢異常必須進行try...catch或throws處理,否則無法通過編譯,不受檢異常沒有這個約束。
不受檢異常包括RuntimeException及其子類 ,下圖不受檢異常未處理可以通過編譯:
受檢異常包括Exception及其子類但不包括RuntimeException及其子類,下面的示例代碼受檢異常無法編譯:
package test; import java.io.IOException; public class ExceptionDemo { public static void main(String[] args) { //JDK定義的受檢異常 //ioexception sqlexception filenotfoudexception 受檢異常,必須對異常進行處理,否則無法編譯 throw new Exception(); //無法編譯 throw new IOException(""); //無法編譯 //自定義受檢異常 throw new CustomCheckedException();//無法編譯 } } /** * 自定義受檢異常 * */ class CustomCheckedException extends Exception{ }
看下官方指導:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
概況起來就是,受檢異常和不受檢異常都是在程序運行時候,出現了錯誤。當調用者接受到不受檢異常時,什么都做不了,比如NullPointerException除了打下日志,調用者無從下手了;當調用者接受到受檢異常時,就知道哪里出了問題該如何處理了,比如接受導FileNotFoundException找不到文件時,調用者就可以換個目錄繼續找文件了。