import java.util.Scanner;
public class Ex {
static void inputException() throws IllegalAccessException{ //声明异常IllegalAccessException
int a[]=new int[3]; //定义包含3个元素的数组
Scanner sc=new Scanner(System.in);
System.out.println("请输入3个整型数据:"); //获取3个元素的值,并计算总和
int i,sum=0,average;
for(i=0;i<3;i++){
a[i]=sc.nextInt();
sum=sum+a[i];
}
System.out.println("请输入除数"); //输入除数,并用总和除以除数
average=sc.nextInt();
average=sum/average;
System.out.println("average="+average);
throw new IllegalAccessException(); //抛出异常IllegalAccessException
}
public static void main(String[] args) {
try{ //try语句组“监督”异常
inputException();
}
catch(ArrayIndexOutOfBoundsException e){ //捕获越界异常IllegalAccessException
System.out.println("数组越界"+e);
}
catch(ArithmeticException e){ //捕获数学异常IllegalAccessException
System.out.println("除数不能为0"+e);
}
catch(IllegalAccessException e){ //捕获异常IllegalAccessException
System.out.println("非法存取"+e);
}
finally{ //finally语句组,输出提示信息
System.out.println("最后一定会被执行的语句");
}
}
public class Ex {
static void inputException() throws IllegalAccessException{ //声明异常IllegalAccessException
int a[]=new int[3]; //定义包含3个元素的数组
Scanner sc=new Scanner(System.in);
System.out.println("请输入3个整型数据:"); //获取3个元素的值,并计算总和
int i,sum=0,average;
for(i=0;i<3;i++){
a[i]=sc.nextInt();
sum=sum+a[i];
}
System.out.println("请输入除数"); //输入除数,并用总和除以除数
average=sc.nextInt();
average=sum/average;
System.out.println("average="+average);
throw new IllegalAccessException(); //抛出异常IllegalAccessException
}
public static void main(String[] args) {
try{ //try语句组“监督”异常
inputException();
}
catch(ArrayIndexOutOfBoundsException e){ //捕获越界异常IllegalAccessException
System.out.println("数组越界"+e);
}
catch(ArithmeticException e){ //捕获数学异常IllegalAccessException
System.out.println("除数不能为0"+e);
}
catch(IllegalAccessException e){ //捕获异常IllegalAccessException
System.out.println("非法存取"+e);
}
finally{ //finally语句组,输出提示信息
System.out.println("最后一定会被执行的语句");
}
}
}
知识点:多异常处理:在一个try语句组后面定义多个catch语句组
心得体会:在try-catch语句组中有可能会抛出多个异常,则需要进行多异常处理,比如,多个输入数据进行相应的多异常处理。