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

1.异常知识点学习实例

代码如下:

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

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

猜你喜欢

转载自www.cnblogs.com/developmental-t-xxg/p/10307637.html