java-異常-自定義異常異常類的丟擲throws
阿新 • • 發佈:2021-11-03
1 package p1.exception; 2 /* 3 * 對於角標是整數不存在,可以用角標越界表示, 4 * 對於負數為角標的情況,準備用負數角標異常來表示。 5 * 6 * 負數角標這種異常在java中並沒有定義過。 7 * 那就按照java異常的建立思想,面向物件,將負數角標進行自定義描述。並封裝成物件 8 * 9 * 這種自定義的問題描述成為自定義異常。 10 * 11 * 注意:如果讓一個類稱為異常類,必須要繼承異常體系,因為只有稱為異常體系的子類才有資格具有可拋性。 12 * 才可以被兩個關鍵字所操作,throws throwExceptionDemo313 * 14 * 15 */ 16 17 class FuShuIndexException extends Exception{ 18 public FuShuIndexException() { 19 // TODO Auto-generated constructor stub 20 } 21 22 FuShuIndexException(String msg){ 23 super(msg); 24 } 25 } 26 class Demo { 27 public static int method(int[] arr,int index) throws FuShuIndexException { 28 29 // System.out.println(arr[index]); 30 if (arr == null) { 31 throw new NullPointerException("陣列的引用不能為空"); 32 } 33 if (index>=arr.length) { 34 throw new ArrayIndexOutOfBoundsException("陣列的角標越界"+index);35 36 } 37 if (index<0) { 38 throw new FuShuIndexException("角標變成負數了"); 39 } 40 return arr[index]; 41 } 42 43 } 44 45 public class ExceptionDemo3 { 46 47 public static void main(String[] args) throws FuShuIndexException{ 48 // TODO Auto-generated method stub 49 int[] arr = new int[3]; 50 // System.out.println(arr[3]); 51 52 Demo d = new Demo(); 53 int num = d.method(arr,-30); 54 System.out.println("num="+num); 55 System.out.println("over"); 56 57 } 58 59 }