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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© filter 中级黑马   /  2012-12-15 09:15  /  1271 人查看  /  1 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

本帖最后由 李志阳 于 2012-12-15 10:54 编辑
  1. package it.cast;

  2. class FuShuException extends RuntimeException//自定义异常
  3.         {        private int num;
  4.                 FuShuException(String msg,int num)
  5.                 {
  6.                         super(msg);//继承父类信息
  7.                         this.num = num;
  8.                 }
  9.                 public int getValue()
  10.                 {
  11.                         return num;
  12.                 }
  13.         }

  14.         class Demo
  15.         {
  16.                 int div(int a,int b) throws Exception
  17.                 {
  18.                         if (b == 0)
  19.                                 throw new Exception("被零除啦!!");//这个异常需要声明并处理
  20.                         if (b < 0)
  21.                                 throw new FuShuException("除数为负数!!",b);
  22.                         return a / b;
  23.                 }
  24.         }

  25.         class  ExceptionDemo4
  26.         {
  27.                 public static void main(String[] args) {
  28.                         
  29.                         
  30.                                 int x = 0;
  31.                                 try {
  32.                                         Demo d = new Demo();
  33.                                        
  34.                                         x = d.div(4,-1);
  35.                                 } catch (Exception e) {
  36.                                         // TODO Auto-generated catch block
  37.                                         System.out.println(e.toString());
  38.                                 }
  39.                         
  40.                                 // TODO Auto-generated catch block
  41.                                 
  42.                         System.out.println("x = " + x);
  43.                 }
  44.         }
复制代码
有点不太明白,为什么传入4,-1,两个参数,程序不会停止,依然可以运行并打印x=0??出现除数负数的时候不是抛出RuntimeException类异常吗?程序应该停止的啊,求解答:)

评分

参与人数 1技术分 +1 收起 理由
古银平 + 1 神马都是浮云

查看全部评分

1 个回复

倒序浏览
我运行了一下确实会抛出异常啊,但是程序遇到异常时并不是停止而是不在执行try块中的代码,所以输出结果是初始值0
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马