文章出處
文章列表
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塊會執行,所以輸出“捕獲異常”。
文章列表
全站熱搜