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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© Rockray 高级黑马   /  2013-10-30 20:11  /  990 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 Rockray 于 2013-10-31 09:30 编辑
  1. class Demo {
  2.         public static void func(){
  3.                 try {
  4.                         throw new Exception();
  5.                         System.out.println("A");
  6.                 }
  7.                 catch(Exception e) {
  8.                         System.out.println("B");
  9.                 }
  10.         }
  11.         public static void main(String[] args) {
  12.                 try {
  13.                         func();
  14.                 }
  15.                 catch(Exception e) {
  16.                         System.out.println("C");
  17.                 }
  18.                 System.out.println("D");
  19.         }
  20. }
复制代码
上面的代码中为什么会出现如下编译错误呢?


而下面的代码一样没执行到一个输出语句,却编译通过了,这是什么原因?
  1. class ExceptionDemo {
  2.         public static void main(String[] args){
  3.                 Demo d = new Demo();
  4.                
  5.                 try{
  6.                         int f = d.div(5,0);
  7.                         System.out.println(f); //同样没被执行到,为什么编译通过了,而上面的代码编译失败
  8.                 }
  9.                 catch(ArithmeticException e){
  10.                     System.out.println(e.toString());
  11.                         System.out.println("除零啦");
  12.                 }
  13.                
  14.                 System.out.println("over");
  15.         }
  16. }
  17. class Demo {
  18.         int div(int a,int b) throws ArithmeticException {
  19.                 return a/b;   //会出现算数异常,除数不为零
  20.         }
  21. }
复制代码

评分

参与人数 1技术分 +1 收起 理由
杨增坤 + 1

查看全部评分

4 个回复

倒序浏览
本帖最后由 未知数|X| 于 2013-10-30 20:29 编辑

   try {

                        throw new Exception();//执行到这时就会抛出异常也就是说它下面的语句永远不会执行到的,你在它下面写 首先编译就不会通过的

                        System.out.println("A");

                }
try{

int f = d.div(5,0);//这是正常流程代码下面的会继续执行

System.out.println(f);  

}

评分

参与人数 1技术分 +1 收起 理由
杨增坤 + 1

查看全部评分

回复 使用道具 举报
上面报错的原因是: throw new Exception();表示一定会出异常,直接跳转到catch语句处理,而执行不到下面的 System.out.println("A");语句
而 System.out.println(f); 没有报错,是因为int f = d.div(5,0); 可能出异常也可能不出异常,下面这句话是有可能执行到的System.out.println(f);所以会出现你上面的情况!
希望对你有帮助!



回复 使用道具 举报
那个语句在抛出异常之后一定不会执行
回复 使用道具 举报
try里面你都抛了,咋行
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马