1. 程式人生 > 其它 >java-異常-原理異常物件的丟擲throw

java-異常-原理異常物件的丟擲throw

 1 class Demo {
 2     public static int method(int[] arr,int index) {
 3         
 4 //        System.out.println(arr[index]);
 5         if (arr == null) {
 6             throw new NullPointerException("陣列的引用不能為空");
 7         }
 8         if (index>=arr.length) {
 9             throw new ArrayIndexOutOfBoundsException("陣列的角標越界"+index);
10 11 } 12 if (index<0) { 13 throw new ArrayIndexOutOfBoundsException("陣列的角標不能為負數"+index); 14 } 15 return arr[index]; 16 } 17 18 } 19 20 public class ExceptionDemo2 { 21 22 public static void main(String[] args) { 23 // TODO Auto-generated method stub
24 int[] arr = new int[3]; 25 // System.out.println(arr[3]); 26 27 Demo d = new Demo(); 28 int num = d.method(null,-30); 29 System.out.println("num="+num); 30 System.out.println("over"); 31 32 } 33 34 }
ExceptionDemo2