Java教程

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

 

这篇关于java-异常-原理异常对象的抛出throw的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!