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

© _Water 中级黑马   /  2014-4-3 22:06  /  1042 人查看  /  2 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

/*
Exception 中有一个特殊的类异常RuntimeException
运行时异常。

如果在函数内抛出该异常,函数上可以不用声明,编译一样通过。

如果在函数上声明了该异常,调用者可以不用进行处理,编译一样通过。

之所以不用在函数上声明,是因为不需要让调用者处理。
当该异常发生,希望程序停止。因为在运行时,出现了无法继续运算的情况,希望停止程序后,对代码进行修正。

自定义异常时:如果此异常的发生,无法在继续进行运算,
就让自定义异常继承RuntimeException。


对于异常分两种:
1.编译时被检测的异常。
class Demo1
{
        int div(int a ,int b)throws Exception
        {
                if(b==0)
                        throw new Exception("除数为0");//ArithmeticException---->>Exception,一定要在函数上声明
                        //同时调用者也要进行处理(要不抛出,要不try处理)
        }
}
2.编译时不被检测的异常(运行时异常,RuntimeException以及其子类)
*/

class FushuException extends RuntimeException
{
        FushuException (String msg)
        {
                super(msg);
        }
}
class Demo
{
        int div (int a,int b)
        {
                if (b==0)
                        throw new ArithmeticException("被0除了");
                if (b<=0)
                        throw new FushuException("除数为负数了");
                return a/b;
        }
}

class ExceptionDemo2
{
        public static void main(String[] args)
        {
                Demo d =new Demo();

                int x =d.div(4,-2);
                System.out.println("x="+x);
                System.out.println("Hello World!");
        }
}

评分

参与人数 1黑马币 +2 收起 理由
ifuzhen + 2 赞一个!

查看全部评分

2 个回复

倒序浏览
很好,学习了
回复 使用道具 举报
学习!!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马