標籤:
第11章 異常處理
一、異常的分類
1、可控式異常:
(1)IOException:當發送某種I/O的異常;
(2)SQLException:關於資料庫訪問或其他錯誤的異常
(3)ClassNotFoundException:類沒有找到的異常
(4)NoSuchFieldException:類不包含指定名稱的欄位時的異常
(5)NoSuchMethodException:無法找到某一方法時候的異常
1 public class Ex1 { 2 3 private int num=10; 4 public int getNum(){ 5 return this.num; 6 } 7 public void setNum(int num){ 8 this.num=num; 9 }10 public Ex1(){11 try{12 Class.forName("Ex123"); //嘗試裝載類13 }catch(ClassNotFoundException e){ //捕獲異常14 e.printStackTrace(); //異常的輸出方法15 }16 System.out.println("測試!");17 }18 19 public static void main(String[] args) {20 // TODO Auto-generated method stub21 Ex1 test=new Ex1();22 test.setNum(888);23 System.out.println(test.getNum());24 }25 }
2、運行時異常
(1)IndexOutOfBoundsException:集合或數組的索引超出範圍的異常
(2)NullPointerException:程式在需要對象的時候使用了null的異常
(3)ArithmeticException:數學運算的異常
(4)IllegalArgumentException:方法傳遞了非法的參數
(5)ClassCastException:將對象強制換換成不是執行個體的子類的異常
1 public class Exc2 { 2 int[] number={100,80,50,70,20,60}; 3 public void setNum(int index,int value){ 4 number[index]=value; 5 } 6 public int getNum(int index){ 7 return number[index]; 8 } 9 public static void main(String[] args) {10 Exc2 test=new Exc2();11 for(int i=0;i<=10;i++){12 try{13 System.out.println(test.getNum(i));14 System.out.println("第"+i+"個數組元素正常顯示");15 }catch(Exception e){16 e.printStackTrace();17 System.out.println("第"+i+"個元素無法讀取!");18 break;19 }20 }21 }22 }
二、處理異常
對於程式中可能發生異常的語句,可以將其添加到try語句塊中,並用catch語句塊進行相應處理。有try-catch語句,和try-catch-finally語句。
其中finally語句塊中是無論try語句塊中程式是否發生異常都會執行的代碼。
三、實戰練習
1 /** 2 * 編寫一個異常類MyException,再編寫一個Student類,其中有一個產生異常的speak(int m)方法 3 * 當m大於1000時,方法拋出MyException對象 4 * 通過主類測試 5 * @author TS 6 */ 7 public class Test{ 8 public class MyException extends Exception{ 9 public MyException(int i){10 System.out.println("發生異常!i的值不能大於1000!");11 System.out.println("目前i值為"+i);12 }13 }14 public class Student{15 public void speak(int m) throws MyException{16 if(m>1000){17 throw new MyException(m);18 }else{19 System.out.println("未發現異常!");20 }21 }22 }23 public static void main(String[] args){24 Test test=new Test();25 Student stu=test.new Student();26 try{27 stu.speak(1001);28 }catch(MyException ex){29 ex.printStackTrace();30 }31 }32 }
1 /** 2 * 建立Number類,通過類的count()方法得到任意兩個數相加的結果 3 * 如果向count()方法傳遞負數,則拋出自訂異常 4 * 在主類中測試 5 * @author TS 6 */ 7 public class Test { 8 public class Number{ 9 long count(long m,long n) throws MyException{10 if((m<0)||(n<0)){11 throw new MyException();12 }else{13 System.out.println("正確返回!結果為"+(m+n));14 return m+n;15 }16 }17 }18 public class MyException extends Exception{19 public MyException(){20 System.out.println("此處拋出自訂異常MyException!");21 System.out.println("提醒:加數中有負數!");22 }23 }24 public static void main(String[] args){25 Test test=new Test();26 Number num=test.new Number();27 try{28 num.count(12, -15);29 }catch(MyException e){30 e.printStackTrace();31 }32 33 }34 35 }
《Java從入門到精通》第十一章學習筆記