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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© linder_qzy 中级黑马   /  2015-3-10 16:02  /  510 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

RuntimeException

Exception中有一个特殊的子类异常RuntimeException运行时异常。
如果在函数内抛出该异常,函数上可以不用声明,编译一样通过。如果在函数上声明了该异常,调用者可以不用进行处理,编译一样通过。
之所以不用在函数声明,是因为不需要让调用者处理。当该异常发生希望程序停止。因为在运行时出现了无法继续运算,停止程序后对代码进行修正。

自定义异常时:如果该异常的发生不能再继续进行运算,就让自定义异常继承RuntimeException。

对于异常分两种
1.编译时被检测的异常
定义的方法中抛出异常,调用该方法的成员必须处理该异常。
2.编译时不被检测的异常(运行时异常。RuntimeException及其子类)

总结:简单的说运行时的自定义异常如果必须通过修改代码解决的异常要继承RuntimeException;
如果不用修改代码就能解决的自定义异常继承Exception。
记住一点:catch是用于处理异常的,没有catch就代表异常没有被处理过,如果异常时检测时异常那么必须声明。
  1. class FuShuException extends RuntimeException
  2. {
  3.         FuShuException(String msg)
  4.         {
  5.                 super(msg);
  6.         }
  7. }
  8. class Demo
  9. {
  10.         int div(int a,int b)//throws Exception 函数不用在向上抛了
  11.         {
  12.                 if(b<0)
  13.                         throw new FuShuException("出现负数异常");
  14.                 if(b==0)
  15.                         throw new ArithmeticException("被零除了");
  16.                 return a/b;
  17.         }
  18. }
  19. class Demo04_ExceptionRunTime
  20. {
  21.         public static void main(String[] args)
  22.         {
  23.                 /*RuntimeException在调用方法中也不用在做异常处理了,
  24.                  一旦发生了RuntimeException程序就会挺住了,后续的代码都不会在执行。
  25.                  */
  26.                 Demo d = new Demo();       
  27.                 int x = d.div(4,-9);
  28.                 System.out.println("x="+x);
  29.                 System.out.println("over!");
  30.         }
  31.         /*运行结果
  32.          * heima.day01.FuShuException: 出现负数异常
  33.                            at heima.day01.Demo.div(Demo04_ExceptionRunTime.java:36)
  34.                            at heima.day01.Demo04_ExceptionRunTime.main(Demo04_ExceptionRunTime.java:48)
  35.              Exception in thread "main"
  36.          * */
  37. }
复制代码

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马