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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© caobin 中级黑马   /  2014-12-3 10:28  /  1292 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

就像除数不能为0 一样,我们自己定义的除数不能为负数为什么不能也自动抛出?除数为0的arithmeticexception为什么会自动抛出?

  1. class ExceptionTest
  2. {
  3.                
  4.         public static void main(String[] args)
  5.         {
  6.                                 Demo d = new Demo();
  7.                 int x = d.div(5,-2);
  8.                                 System.out.println(x);
  9.         }
  10. }
  11. class FushuException extends RuntimeException
  12. {
  13.         FushuException(String message)
  14.         {
  15.                 super(message);
  16.         }
  17. }
  18. class Demo
  19. {
  20.                 int div(int a,int b)
  21.                 {
  22.                         if(b<0)
  23.                                 throw new FushuException("除数不能为负数");
  24.                         return a/b;
  25.                 }
  26. }
复制代码



评分

参与人数 1技术分 +1 收起 理由
杨佳名 + 1

查看全部评分

3 个回复

倒序浏览
因为你继承的是RuntimException,而ArithmeticException是RuntimeException的子类。java虚拟机可以对RuntimeException自动处理。

评分

参与人数 1技术分 +1 收起 理由
杨佳名 + 1

查看全部评分

回复 使用道具 举报
楼主,我复制了你的代码,运行了一下,发现可以抛出你自定义的异常,如图。

ExceptionTest.jpg (50.41 KB, 下载次数: 45)

ExceptionTest.jpg
回复 使用道具 举报
彭柏良 发表于 2014-12-3 12:32
因为你继承的是RuntimException,而ArithmeticException是RuntimeException的子类。java虚拟机可以对Runtim ...

我突然明白了 哈哈 thank you
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马