示例程序1

 1 public class EmbededFinally {
 2 
 3     
 4     public static void main(String args[]) {
 5         
 6         int result;
 7         
 8         try {
 9             
10             System.out.println("in Level 1");
11 
12            
13              try {
14                 
15                 System.out.println("in Level 2");
16   // result=100/0;  //Level 2
17                
18                  try {
19                    
20                      System.out.println("in Level 3");
21                       
22                      result=100/0;  //Level 3
23                 
24                 } 
25                 
26                 catch (Exception e) {
27                     
28                     System.out.println("Level 3:" + e.getClass().toString());
29                 
30                 }
31                 
32                 
33                 finally {
34                     
35                     System.out.println("In Level 3 finally");
36                 
37                 }
38                 
39                
40                 // result=100/0;  //Level 2
41 
42             
43                 }
44             
45             catch (Exception e) {
46                
47                  System.out.println("Level 2:" + e.getClass().toString());
48            
49              }
50              finally {
51                 
52                 System.out.println("In Level 2 finally");
53            
54              }
55              
56             // result = 100 / 0;  //level 1
57         
58         } 
59         
60         catch (Exception e) {
61             
62             System.out.println("Level 1:" + e.getClass().toString());
63         
64         }
65         
66         finally {
67            
68              System.out.println("In Level 1 finally");
69         
70         }
71     
72     }
73 
74 }

结果截图

分析

当有多层嵌套的finally时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

在一些特殊情况下finally语句块不一定会执行

如:

 1 public class SystemExitAndFinally {
 2 
 3     public static void main(String[] args)
 4     {
 5         try{
 6 
 7             System.out.println("in main");
 8             throw new Exception("Exception is thrown in main");
 9             //System.exit(0);
10 
11         }
12         catch(Exception e)
13         {
14             System.out.println(e.getMessage());
15             System.exit(0);
16         }
17         finally
18         {
19             System.out.println("in finally");
20         }
21     }
22 
23 }

结果截图

 

posted on 2015-11-13 15:57  卫平公  阅读(185)  评论(0编辑  收藏  举报