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

© Tauruszzy 中级黑马   /  2015-5-10 10:08  /  180 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

class Demo
{
        int div(int a,int b)//函数内声明了,但函数上没有声明
        {
                if(b<0)
                        throw new ArithmeticException();
                return a/b;
        }
}

class  RuntimeExceptionDemo
{
        public static void main(String[] args)
        {
                Demo d=new Demo();
                int x=d.div(4,-1);
                System.out.println("x="+x);
        }
}
程序运行结果:编译通过,运行提示错误。
----------------------------------------------------------------------------------------------------------
class Demo
{
        int div(int a,int b)
        {
                if(b<0)
                        throw new Exception();
                return a/b;
        }
}

class  RuntimeExceptionDemo
{
        public static void main(String[] args)
        {
                Demo d=new Demo();
                int x=d.div(4,-1);
                System.out.println("x="+x);
        }
}
程序运行结果:
编译失败。
------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
总结:ArithmeticException与Exception有不同之处。ArithmeticException是RuntimeException的子类,   而RuntimeException在函数内抛出时,在他所在的函数上可以不声明,但编译依然成功,但运行时失败,这时程序员需要对程序代码进行修改。

评分

参与人数 1技术分 +1 收起 理由
lwj123 + 1

查看全部评分

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马