java-异常-finally代码块

 1 package p1.exception;
 2 
 3 
 4 class Demo_0{
 5     public int show(int index) throws ArrayIndexOutOfBoundsException{
 6         if (index<0) {
 7             throw new ArrayIndexOutOfBoundsException("越界了");
 8         }
 9         int[] arr = new int[3];
10         return arr[index];
11     }
12 }
13 public class ExceptionDemo5 {
14 
15     public static void main(String[] args) {
16         // TODO Auto-generated method stub
17         Demo_0 d = new Demo_0();
18         try {
19             int num = d.show(1);
20             System.out.println("num="+num);
21         } catch (ArrayIndexOutOfBoundsException e) {
22             // TODO: handle exception
23             System.out.println(e.toString());//开发时不要写输出语句,没有控制台
24 //            return;//这里停止执行
25 //            System.exit(0);//退出jvm,后面都不执行了(包括finally)
26         }finally{//但finally是一定执行的, 通常用于关闭(释放)资源
27             System.out.println("finally");
28         }
29         System.out.println("over");
30     }
31 
32 }
33 
34 /*
35  * 连接数据库
36  * 查询。Exception
37  * 关闭连接。(无论出现没出现异常 都要用到)所以用finally
38  * 
39  */
40 
41 /*
42  * try catch finally 代码块组合特点:
43  * 
44  * 1,
45  * try catch finally
46  * 
47  * 2,try catch(多个)当没有必要资源需要释放时,可以不用定义finally。
48  * 
49  * 3,
50  * try finally 异常无法直接catch处理,但是资源需要关闭
51  * 
52  * void show()throws Exception//没catch就没处理所以方法也要声明
53  * {
54  *         try{
55  *             //开启资源
56  *             throw new Exception();//出异常了可以留给别人处理,但是资源是自己开启的必须自己关,所以在finally里关
57  *         
58  *         }
59  *         finally{
60  *             //关闭资源。
61  *         }
62  * }
63  * 
64  */
ExceptionDemo5

 

posted @ 2021-11-04 21:38  doremi429  阅读(23)  评论(0)    收藏  举报