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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

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

class Demo
{
        int div(int a,int b)throws Exception//throws Exception表示这段程序可能会有问题
        {
                return a/b;
        }
}

class ExceptionDemo
{
        public static void main(String[]args)
        {
                Demo d=new Demo();
                int x =d.div(4,1);//程序运行到此处会给出,如下提示:未报告的异常错误,必须对其进行捕捉或
                                          //声明,表明解决的办法有两种:捕捉,声明。
                System.out.println("over"+x);
        }
}
-------------------------------------
/*
声明的解决方法如下:在调用声明了throws Exception方法的函数上也声明throws Exception,表示不做处理,也抛出
*/
class Demo
{
        int div(int a,int b)throws Exception
        {
                return a/b;
        }
}

class ExceptionDemo
{
        public static void main(String[]args)throws Exception//声明方法在此处
        {
                Demo d=new Demo();
                int x =d.div(4,1);
                System.out.println("over"+x);
        }
}
备注:程序能够通过编译,并执行,用声明的方法解决了此问题。
------------------------------------------------------------------------------------------------------------

class Demo
{
        int div(int a,int b)throws Exception
        {
                return a/b;
        }
}

class ExceptionDemo
{
        public static void main(String[]args)throws Exception
        {
                Demo d=new Demo();
                int x =d.div(4,0);//把1变为0,编译通过,运行出现问题,即执行到此处把问题抛给了虚拟机
                System.out.println("over"+x);
        }
}

------------------------------------------------------------------------------------------------------------
/*
第二种解决方法:捕捉
*/
class Demo
{
        int div(int a,int b)throws Exception
        {
                return a/b;
        }
}

class ExceptionDemo
{
        public static void main(String[]args)
        {
                Demo d=new Demo();
                try//程序没有报错,是因为此处进行了捕捉
                {
                        int x =d.div(4,1);//因为没有错误所以程序运行了下面的输出语句,当1变为0时这里下面的输           
                                                  //出语句不执行
                        System.out.println("x="+x);
                }
                catch (Exception e)//为1时没有错误,此处不执行,当1变为0时,这里执行
                {
                        System.out.println(e.toString());
                }
                System.out.println("over");//执行
        }
}


以上就是在有可能出现异常的方法声明了throws Exception后的两种处理方法,建议使用捕捉方法,因为声明方法没有对问题进行处理,显然有点不负责任。

8 个回复

倒序浏览
是的。。
回复 使用道具 举报
赞!!!!!
回复 使用道具 举报
视频当时看的有点迷糊,现在明白了,不错!
回复 使用道具 举报
现在看还是很乱呀
回复 使用道具 举报
看来看去不知道想表达什么啊。。。。。。
回复 使用道具 举报
看来看去不知道想表达什么啊。。。。。。不过看起来很屌的样子
回复 使用道具 举报
异常还没学...
回复 使用道具 举报
不错~谢谢分享!!
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马