import java.util.Scanner;
public class ExceptionTest1 {
static void inputException() throws IllegalAccessException{//声明异常IllegalAccessException
int a[]=new int[3];//定义包含3个元素的数组
Scanner sc=new Scanner(System.in);
System.out.println("输入3个整型数据:");
int i,sum=0,average;
for(i=0;i<3;i++){ //循环输入3个整型数据
a[i]=sc.nextInt();//输入三个整型
sum=sum+a[i];//计算总和
}
System.out.println("请输入除数:");
average=sc.nextInt();
average=sum/average;//总和除以除数
System.out.println("输出除数:"+average);
throw new IllegalAccessException();//抛出异常IllegalAccessException
}
public static void main(String[] args) {
// TODO 自动生成的方法存根
try{//为方法inputException()进行监听
inputException();
}
catch(ArrayIndexOutOfBoundsException e){//捕获异常,并输入错误提示
System.out.println("数组越界"+e);
}
catch(ArithmeticException e){
System.out.println("除数不能为0"+e);//捕获数学运算异常ArithmeticException
}
catch( IllegalAccessException e){//捕获异常ArithmeticException
System.out.println("非法存取"+e);
}
finally{//最终处理,输出相应的信息提示
System.out.println("最后一定被执行的语句");
}
}
}
运行结果:
分析:程序通过了try语句组中的inputException( ),实现了多个异常处理,如果非法中出现了数组下标异常,则该异常会被catch(ArrayIndexOutOfBoundsException e)捕获;如果出现除数为0的异常,则会被catch(ArithmeticException e)捕获;如果抛出的异常IllegalAccessException(),则会被catch(IllegalAccessException e)捕获。
知识要点:多异常处理机制中,要注意以下方面:
1)catch语句组中的处理程序应按照异常的不同而执行不同的异常处理操作。
2)由于try语句组中的异常是按照catch语句组的先后排列顺序来进行匹配的,所以在处理多异常时要注意各个catch语句间的排列顺序。