黑马程序员技术交流社区

标题: 异常处理之ArithmeticException问题 [打印本页]

作者: 张亭    时间: 2012-4-25 17:53
标题: 异常处理之ArithmeticException问题
今天学习毕老师JavaSE-第09天-11-面向对象(RuntimeException)的课程

边学边跟着写了如下代码:
class D {
    public int div(int a, int b)  {//第二行
         if(0==b)
               throw new ArithmeticException("000000000");
         return a/b;
    }
}
class A {
    public static void main(String[] args) {
         D d = new D();
         int x = d.div(4,0);
     }
}

课程中老师讲ArithmeticExceptionRuntimeException的子类
不用在函数上声明也可编译通过,
问题来了,
以上代码我怎么也不能编译通过,报错信息:
A.java:4: 错误: 未报告的异常错误ArithmeticException; 必须对其进行捕获或声明以便
抛出
                        throw new ArithmeticException("000000000");
                        ^
1 个错误

相当郁闷啊,把ArithmeticException换成RuntimeException却是OK的.
把第二行改为 public static void main(String[] args) throws ArithmeticException {
也还是不行,只有加上上面语句之后再在下面的语句上TRY一下才能通过编译.

不知道是怎么回事,也不晓得是不是个案,发出来大家可以试试,也许是我机器问题(WIN7+jdk1.7.0_03)

当然如果有人能帮忙解惑就更好了{:soso_e183:}


作者: 刘基军    时间: 2012-4-25 18:08
我用win7+jdk1.6,UtlraEdit测试,一切正常...
作者: 光sail    时间: 2012-4-25 18:26

我这能够编译通过,不管文件名是A还是D,我xp的系统和jdk1.6
作者: 张亭    时间: 2012-4-25 18:31
经过一番研究才找到了原因,发出来大家参考一下:

原来是这样的,在一楼代码之前,我编译过如下代码:

class ArithmeticException extends Exception {
      ArithmeticException(String msg) {
              super(msg);
      }
}
class D {
    public int div(int a, int b) throws ArithmeticException {
         if(0==b)
               throw new ArithmeticException("000000000");
         return a/b;
    }
}
class A {
    public static void main(String[] args) {
         D d = new D();
         try {
               int x = d.div(4,0);
         }
         catch (ArithmeticException e) {
                System.out.println(e.toString());
         }
     }
}
相当于自己重写了一个ArithmeticException类
这样一来,在源目录下就产生了一个ArithmeticException.class的文件,然后在编译一楼的代码时,就直接在同目录下找到了这个文件,结果就报错啦!!
嘿嘿,算是累积了一点经验吧,共勉之!!!


作者: 索学超    时间: 2012-4-25 18:32
//代码:
class D{
        public int div(int a ,int b)        
        {                
                if(0==b)        
                            throw new ArithmeticException("0000000000");
                return a/b;
        }
}
class A {
        public static void main(String[] args)
        {
                D d = new D();
                int x = d.div(4, 0);
                System.out.println(x);
        }
  }
//输出结果
Exception in thread "main" java.lang.ArithmeticException: 0000000000
        at D.div(A.java:7)
        at A.main(A.java:16)
这算通过不
如果算的话,可能是你没弄好吧




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2