exception测试实验(研究finally的作用)

 1 public class Exception {
 2 
 3     public static void main(String[] args) {
 4         System.out.println(method());
 5     }
 6 
 7     public static int method() {
 8         try {
 9             int x[] = null;
10             x.toString();
11             System.out.println("try结束!");
12             return 10;
13         } catch (ArrayIndexOutOfBoundsException e) {
14             System.out.println(e.toString());
15             System.out.println("catch结束!");
16         } finally {
17             System.out.println("finally结束!");
18 
19         }
20 
21         System.out.println("测试结束!");
22         return 30;
23     }
24 
25 }

输出结果:

finally结束!
Exception in thread "main" java.lang.NullPointerException
    at Exception.method(Exception.java:11)
    at Exception.main(Exception.java:5)

如果把第13行catch括号里换成NullPointerException e

则输出结果:

java.lang.NullPointerException
catch结束!
finally结束!
测试结束!
30

 

实验结论:

如果正确地catch掉了异常,则finally对程序没有任何影响。

反之,finally外的语句不会执行。

posted @ 2021-01-25 21:31  是逸仙呀  阅读(128)  评论(1编辑  收藏  举报