黑马程序员技术交流社区

标题: 有关异常处理的问题 [打印本页]

作者: filter    时间: 2012-12-15 09:15
标题: 有关异常处理的问题
本帖最后由 李志阳 于 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类异常吗?程序应该停止的啊,求解答:)
作者: 张胜格    时间: 2012-12-15 10:26
我运行了一下确实会抛出异常啊,但是程序遇到异常时并不是停止而是不在执行try块中的代码,所以输出结果是初始值0




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