ArrayIndexOutOfBoundsException:数组下标越界
/*2018.5.20
* ArrayIndexOutOfBoundsException:创建一个由100个随机数选择的整数构成的数组。提示用户输入数组的下标,然后显示对应的元素值。如果下标越界,就显示消息Out Of Bounds。* 知识点:异常的基本思路,声明异常-抛出异常-捕获异常
*/
import java.util.*;
public class ch12_3_1 {
public static void main(String[] args)throws ArrayIndexOutOfBoundsException //声明异常类型
{
int [] list= new int[100];
for(int i=0;i<list.length;i++) //建立数组
list[i]=(int)(Math.random()*100);
int index=0;
System.out.println("Enter index:");
try
{
index=new Scanner(System.in).nextInt();
if(index>=100||index<0) //发现异常并抛出
throw new ArrayIndexOutOfBoundsException();
System.out.println(list[index]);
}
catch(ArrayIndexOutOfBoundsException ex) //捕获异常进行处理
{
System.out.println("Out Of Bounds!"); //输出异常情况
throw ex; //处理不了就再次抛出,不要随便处理
}
}
}