异常处理中的finally

  以前看书时书上讲的当出现异常后,后面的代码就不会执行了,这时如果写在finally中,则还可执行。但是在实际的项目经历中有几次我发现不写finally,后面的代码也是能执行的,感觉很奇怪,今天又验证了一下:

1、有不少情况异常出现之后,后边的代码仍然能够执行,如:

 1 public class TestException{
 2     
 3     public static void main(String args[]) {
 4         String friends[]={"Lily","Mary","Jim"};
 5         try{
 6             
 7          for(int i=0;i<4;i++){
 8              System.out.println(friends[i]);    
 9             
10          }
11          
12         }
13         catch(ArrayIndexOutOfBoundsException ae){
14             System.out.println("出错了!");                    
15         }
16     
17                 System.out.println("\nThis is the end.");    
18 
19     }    
20     
21 }

运行结果是:

2、如果catch里面有return语句,那么是不会往下执行的。这时如果(L17)加入finally,则是可以执行的。

3、如果catch中又出现异常,这时则不能执行后面的代码(此处为L19).

 1 public class TestException{
 2     
 3     public static void main(String args[]) throws Exception{
 4         String friends[]={"Lily","Mary","Jim"};
 5         try{
 6             
 7          for(int i=0;i<4;i++){
 8              System.out.println(friends[i]);    
 9             
10          }
11          
12         }
13         catch(ArrayIndexOutOfBoundsException ae){
14             System.out.println("出错了!");        
15             //ae.printStackTrace();
16         throw new Exception("haohaohao");
17         }
18     
19                 System.out.println("\nThis is the end.");    
20 
21     }    
22     
23 }

运行结果为

若将L19加进finally中,则可以执行到此句,运行结果为:

  欢迎补充……

原文地址:https://www.cnblogs.com/qingxinblog/p/2819855.html