文章出處

public class Test1 {
    public static void main(String[] args) {
        try {
            add(1);
            System.out.println("正常輸出結束");
        } catch (Exception e) {
            System.out.println("捕獲異常");
        }
    }

    public static void add(int num) throws Exception
    {
        if(num==1)
            throw new Exception();
            
        System.out.println("add異常");
    }
}

輸出結果

捕獲異常

原因

因為在執行main()方法調用了add()方法,add方法執行步驟是先判斷形參的值是(1),判斷輸入的為1,拋出異常,下面的代碼都不會再執行,然后把異常拋給了他的方法的異常集,因為該方法有異常集,所以在main()方法中需要加try-catch塊,或者給main()方法添加異常集,由于添加異常集的話,該異常相當于重新給了java虛擬機,還是無法給出人性化的提示,所以只能加try-catch塊,因為該方法傳入的參數導致該方法出現了異常,所以在main()方法中的catch塊會執行,所以輸出“捕獲異常”。


文章列表


不含病毒。www.avast.com
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()