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

 

上一篇:800-C++ throw(抛出异常)详解


下一篇:Day 6 HomeWork-ConstantPropagation