Java-- 异常之使用finally进行清理

  对于一些代码,可能会希望无论try块中的异常是否抛出,它们都能得到执行。这通常适用于内存回收之外的情况。为了达到这样的效果,可以在异常处理程序后面加上finally子句。如下:

 1 try{
 2 
 3   //The guarded region: Dangerous activities
 4 
 5   //taht might throw A,B, or C
 6 
 7 }catch(A a1){
 8 
 9   //handler for situation A
10 
11 }catch(B b1){
12 
13   //Handler for situation B
14 
15 }catch(C c1){
16 
17   //Handler for situtation C
18 
19 }finally{
20 
21   //activities that happen every time
22 
23 }

为了证明finally总能运行,可以试试如下程序:
 1 package com.exceptions;
 2 
 3 class ThreeException extends Exception{}
 4 public class FinallyWorks {
 5     static int count = 0;
 6     public static void main(String[] args){
 7         while(true){
 8             try{
 9                 if(count++ ==0)
10                     throw new ThreeException();
11                 System.out.println("No Exception");
12             }catch(ThreeException e){
13                 System.out.println("ThreeException");
14             }finally{
15                 System.out.println("In finally clause");
16                 if(count == 2) break;
17             }
18         }
19     }
20 }

结果如下:

1 ThreeException
2 In finally clause
3 No Exception
4 In finally clause

 

 

posted @ 2014-06-26 21:58  FireEgg  阅读(303)  评论(0编辑  收藏  举报