Java核心技术36讲----------Exception和Error有什么区别

1.异常知识点学习实例

代码如下:

 1 package fromnet;
 2 
 3 
 4 /**
 5  * 参考链接:https://blog.csdn.net/qq_18505715/article/details/73196421
 6  * @author MSI-Gaming
 7  *
 8  */
 9 
10 public class ThrowTest1 {
11     
12 // 定义一个方法,抛出 数组越界和算术异常(多个异常 用 "," 隔开)
13     public void Test1(int x) throws ArrayIndexOutOfBoundsException,ArithmeticException{
14         
15         System.out.println(x);
16         
17         if(x == 0){
18 
19             System.out.println("没有异常");
20             return;
21         }
22         
23         //数据越界异常
24         else if (x == 1){
25 
26             int[] a = new int[3];
27              a[3] = 5;
28         }
29         
30         //算术异常
31         else if (x == 2){
32 
33             int i = 0;
34             int j = 5/0;
35         }
36     }
37     
38     public static void main(String[] args) {
39         
40         //创建对象
41         ThrowTest1 object = new ThrowTest1();
42         
43         // 调用会抛出异常的方法,用try-catch块
44         try {
45             object.Test1(0);
46         } catch (Exception e) {
47             // TODO Auto-generated catch block
48             e.printStackTrace();
49         }
50         
51         // 数组越界异常
52         try {
53             object.Test1(1);
54         } catch (ArrayIndexOutOfBoundsException e) {
55             System.out.println("数组越界异常:"+e);
56         }
57         
58         // 算术异常
59         try{
60 
61             object.Test1(2);
62 
63         }catch(ArithmeticException e){
64 
65             System.out.println("算术异常:"+e);
66         }
67         
68         System.out.println("有上面的try-catch后,我才可以来");
69       //使用 throw 抛出异常(可以抛出异常对象,也可以抛出异常对象的引用)
70         //这边可去掉try来测试
71         try{
72 
73             ArrayIndexOutOfBoundsException  exception = new ArrayIndexOutOfBoundsException();
74 
75             throw exception;//new ArrayIndexOutOfBoundsException();//去掉这一行就是生吞异常了,不报异常
76 
77         }catch(ArrayIndexOutOfBoundsException e){
78 
79             System.out.println("thorw抛出异常:"+e);
80         }
81 
82         
83     }
84 
85 }

2.分析

#在方法Test1()中,如果不抛出异常,即throws。。。,再在main中调用Test1方法object.Test1(1);就会出现ArrayIndexOutOfBoundsException异常情况,并在控制台中能定位到异常位置。

#在main中自定义异常ArrayIndexOutOfBoundsException  exception,并throw。如果没有catch的话,就会在发生异常情况,而catch后,就会处理catch中的处理语句

参考https://blog.csdn.net/qq_18505715/article/details/73196421

原文地址:https://www.cnblogs.com/developmental-t-xxg/p/10307637.html