1. 程式人生 > >Java- 受檢的異常(checked Exception)

Java- 受檢的異常(checked Exception)

受檢的異常

  • Exception分為兩種
    1. RuntimeException及其子類,可以不明確處理,例如邊界異常,解析整型時格式異常。
    2. 否則,稱為受檢的異常(checked Exception),更好的保護安全性
  • 受檢的異常,要求明確進行語法處理

    • 要麼捕獲(catch)
    • 要麼丟擲(throw):在方法的簽名後面用throws xxx來宣告
      • 在子類中,如果要覆蓋父類的一個方法,若父類中的方法聲明瞭throws異常,則子類的方法也可以throws異常
      • 可以丟擲子類異常(更具體的異常),但不能丟擲更一般的異常
        public class ExceptionTrowsToOther{
            public
        static void main(String[] args){ try{ System.out.println("====Before===="); readFile(); System.out.println("====After===="); }catch(IOException e){ System.out.println(e); }// catch the exception } public static void readFile()throws IOException {// throws exception
        FileInputStream in=new FileInputStream("myfile.txt"); int b; b = in.read(); while(b!= -1) { System.out.print((char)b); b = in.read(); } in.close(); } } -----------OUTPUT----------- ====Before==== java.io.FileNotFoundException: myfile.txt (The system cannot find the file specified)

try…with…resource

try(型別 變數名=new型別() ){
    ...
}

自動添加了finally{ 變數.close(); }對可關閉的資源進行關閉操作

    static String ReadOneLine1(String path){
        BufferedReader br=null;
        try {
            br=new BufferedReader(new FileReader(path));
            return br.readLine();
        } catch(IOException e) {
            e.printStackTrace();
        } finally {
            if(br!=null){
                try{ 
                    br.close();
                }catch(IOException ex){
                }
            }
        }
        return null;
    }
    static String ReadOneLine2(String path)
        throws IOException
    {
        try(BufferedReader br= new BufferedReader(new FileReader(path))){
            return br.readLine();
        }
    }

上面兩個函式ReadOneLine1及ReadOneLine2效果相同。