天天看點

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

11.2 捕獲異常

try{}catch(Throwable e){} 結構

執行過程:

(1)執行try 中的語句

(2) try中語句産生異常則不再執行 try 後續語句,執行 catch 中的語句

(3)try中語句沒有異常則執行完 try 的所有語句, 不執行 catch 中的語句

如果不進行 try…catch 捕獲,則必須使用 throws 向上抛出

11.2.1 捕獲多個異常

寫多個catch 對應不同異常即可

示例代碼:

public class Main {
    public static void main(String[] args) {
        Main solution = new Main();
        try {
            int a = 2;
            if(a==2)
                throw new IOException("123");
            solution.test(1/0);
        } catch (FontFormatException e) {
            System.out.println(ErrorUtil.getAllException(e));
        }catch (ArithmeticException e){
            System.out.println("ArithmeticException:"+ErrorUtil.getAllException(e));
        }catch (Exception e){
            System.out.println("Exception:"+ErrorUtil.getAllException(e));
        }


    }

    private void test(int num) throws FontFormatException {
        if(num==1)
            throw new FontFormatException("test");
    }
}      

異常情況:

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

隐藏:

 if(a==2)

                throw new IOException("123");

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

特别注意,不能把Exception 放在 ArithmeticException 前面,父類必須放在後面,否則換一下Exception 和 ArithmeticException 位置,編譯器會給出如下錯誤:

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

11.2.2 再次抛出異常與異常鍊

在catch 塊抛出新異常,使用 initCause 給出具體異常調用鍊

這裡作者給的方法是 initCause, 這樣寫:

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

但是,其實可以這樣寫:

《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊

完整代碼:

public class Main {
    public static void main(String[] args) throws Exception {
        Main solution = new Main();
        try {
            int a = 2;
//            if(a==2)
//                throw new IOException("123");
            solution.test(1/0);
        } catch (FontFormatException e) {
            System.out.println(ErrorUtil.getAllException(e));
        }catch (ArithmeticException e){
            System.out.println("ArithmeticException:"+ErrorUtil.getAllException(e));
            Exception root = new RuntimeException("math check:", e);
            throw new Exception(root);
        }


    }

    private void test(int num) throws FontFormatException {
        if(num==1)
            throw new FontFormatException("test");
    }
}      
《Java 核心技術 卷1》 筆記 第11章 異常、日志、斷言和調試(2)捕獲異常與異常鍊