java-异常-编译时检测异常和运行时异常区别(throws和throw区别)

 1 package p1.exception;
 2 /*
 3  * 对于角标是整数不存在,可以用角标越界表示,
 4  * 对于负数为角标的情况,准备用负数角标异常来表示。
 5  * 
 6  * 负数角标这种异常在java中并没有定义过。
 7  * 那就按照java异常的创建思想,面向对象,将负数角标进行自定义描述。并封装成对象
 8  * 
 9  * 这种自定义的问题描述成为自定义异常。
10  * 
11  * 注意:如果让一个类称为异常类,必须要继承异常体系,因为只有称为异常体系的子类才有资格具有可抛性。
12  *         才可以被两个关键字所操作,throws throw
13  * 
14  * 异常的分类:
15  * 1,编译时被检测异常:只要是Exception和其子类都是,除了特殊子类RuntimeException体系
16  *         这种问题一旦出现,希望在编译时就进行检测,让这种问题有对应的处理方式    
17  *         这样的问题都可以针对性的处理
18  * 
19  * 2,编译时不检测异常(运行时异常):就是Exception中的RuntimeException和其子类
20  *         这种问题的发生,无法让功能继续,运算无法进行,更多是因为调用者的原因导致的,或者引发了内部状态改变导致的(比如多线程时候)
21  *         那么这种问题一般不处理,直接编译通过,在运行时,让调用者调用时的程序强制停止.让调用者对代码进行修正.
22  *
23  *所以自定义异常时,要么继承Exception,要么继承RuntimeException
24  *
25  *throws 和 throw 区别
26  *
27  *1,throws使用在函数上.
28  *    throw使用在函数内.
29  *2,throws抛出的是异常类,可以抛出多个,用逗号隔开.
30  *    throw抛出的是异常对象.
31  *
32  */
33 
34 class FuShuIndexException extends RuntimeException /*Exception*/{//可以改继承运行异常,就不会报编译错误
35     public FuShuIndexException() {
36         // TODO Auto-generated constructor stub
37     }
38     
39     FuShuIndexException(String msg){
40         super(msg);
41     }
42 }
43 class Demo {
44     public static int method(int[] arr,int index) /*throws FuShuIndexException*/ {
45         
46 //        System.out.println(arr[index]);
47         if (arr == null) {
48             throw new NullPointerException("数组的引用不能为空");
49         }
50         if (index>=arr.length) {
51             throw new ArrayIndexOutOfBoundsException("数组的角标越界"+index);
52             
53         }
54         if (index<0) {
55             throw new FuShuIndexException("角标变成负数了");
56         }
57         return arr[index];
58     }
59 
60 }
61 
62 public class ExceptionDemo3 {
63 
64     public static void main(String[] args) /*throws FuShuIndexException*/{
65         // TODO Auto-generated method stub
66         int[] arr = new int[3];
67 //        System.out.println(arr[3]);
68         
69         Demo d = new Demo();
70         int num = d.method(arr,-30);
71         System.out.println("num="+num);
72         System.out.println("over");
73         
74     }
75     
76 }
ExceptionDemo3

 

posted @ 2021-11-03 22:13  doremi429  阅读(87)  评论(0)    收藏  举报