对输入数据进行多个异常处理

来源:互联网 发布:人工智能演讲 编辑:程序博客网 时间:2024/05/16 15:08
package java;import java.util.Scanner;public class yc {    static void inputException()throws IllegalAccessException    {        int a[]=new int[3];        Scanner sc=new Scanner(System.in);        System.out.println("请输入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();     }    public static void main(String[] args) {        // TODO Auto-generated method stub        try {            inputException();        }        catch(ArrayIndexOutOfBoundsException e)        {            System.out.println("数组越界"+e);        }        catch(ArithmeticException e)        {            System.out.println("除数不能为0"+e);        }        catch(IllegalAccessException e)        {            System.out.println("非法存取"+e);        }        finally        {            System.out.println("最后一定会被执行的语句");        }    }}

程序分析:声明异常IllegalAccessException
定义包含3个元素的数组;
获取3个元素的值,并计算总和;
输入除数,并用总和除以除数;finally语句组,输出提示信息;
try语句组“监督”异常;
抛出异常IllegalAccessException;

原创粉丝点击