A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 追逐 高级黑马   /  2014-3-16 11:34  /  582 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
对多异常进行处理。
1,声明异常类,建议声明更为具体的异常,这样处理的可以更具体。
2,对方声明几个异常,就对应有几个catch块。
        如果多个catch块中的异常出现继承关系,父类异常catch块放在最       

下面

建议在进行catch处理时,catch中一定要定义具体处理方式。
不要简单定义一句e.printStackTrace();
也不要简单的书写一条输出语句;
*/
class Demo1 {
       
        //对函数声明并抛出异常
        public int div(int a, int b) throws ArithmeticException, ArrayIndexOutOfBoundsException {
                int[] arr = new int[a];
                System.out.println(arr[4]);
                return a / b;
        }

}

class ExceptionDemo1 {
        public static void main(String[] args) {
                Demo1 d = new Demo1();
                try { //检测异常
                        int x = d.div(2, 1);
                        System.out.println(x);
                } catch(ArithmeticException e) {
                        System.out.println("被0除了");
                        System.out.println(e.getMessage()); //打印异常信息
                        System.out.println(e.toString()); //打印异常名称  异常信息
                        e.printStackTrace(); //打印异常名称  异常信息  异常位置
                } catch(ArrayIndexOutOfBoundsException e) {
                        System.out.println("角标越界了");
                        System.out.println(e.toString());
                } finally {
                        System.out.println("欢迎计算"); //无论是否异常,都输出此语句
                }
        }
}

1 个回复

倒序浏览
嗯嗯 收藏 再看!!!!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马