零EVA

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Exception中有一个特殊的子类异常RuntimeException 运行时异常

  1 如果在函数内抛出该异常,函数上可以不用声明,编译一样通过

  2 如果在函数上声明了该异常,调用者可以不用进行处理,编译一样通过

之所以不用再函数上声明,是因为不需要让调用者处理

当该异常发生,希望程序停止,因为在运行时,出现了无法继续运算的情况,希望停止程序后,对代码进行修正

 

自定义异常时,如果该异常的发生,无法再继续继续进行运算,

就让自定义异常继承RuntimeException

 

对于异常分两种:

  1 编译时被检测的异常

  2 编译时不被检测的异常(运行时异常,就是RuntimeException及其子类)

 1 class NegativaException extends RuntimeException
 2 {
 3     NegativaException(String msg)
 4     {
 5         super(msg);
 6     }
 7 }
 8 class Demo
 9 {
10     int div(int a,int b)
11     {
12         if(b < 0)
13         {
14             throw new NegativaException("出现负数");
15         }
16         if(b == 0)
17             throw new ArithmeticException("被零除");
18         return a/b;
19     }
20 }
21 class ExceptionDemo
22 {
23     public static void main(String[] args)
24     {
25         Demo d = new Demo();
26 
27         int x = d.div(4,-1);
28         System.out.println("x="+x);
29 
30         System.out.println("Over");
31     }
32 }
View Code

 

posted on 2017-06-14 15:07  零EVA  阅读(290)  评论(0)    收藏  举报