finally 用来做什么?

对于没有垃圾回收和析构函数自动调用机制3的语言来说,finally非常重要。它能使程序
员保证:无论try块里发生了什么,内存总能得到释放。但Java有垃圾回收机制,所以内
存释放不再是问题。况且,Java也没有析构函数可供调用。那么,Java在什么情况下才
能用到finally呢?
 
当你要把除内存之外的资源恢复到它们的初始状态时,就要用到 finally 子句。这种需要
清理的资源包括:已经打开的文件或网络连接,你在屏幕上画的图形,甚至可以是外部
世界的某个开关,如下面例子所示:


//: c09:Switch.java
public class Switch {
private boolean state = false;
public boolean read() { return state; } 
public void on() { state = true; }
public void off() { state = false; }
} ///:~


//: c09:OnOffException1.java
public class OnOffException1 extends Exception {} ///:~ 
//: c09:OnOffException2.java
public class OnOffException2 extends Exception {} ///:~ 


//: c09:OnOffSwitch.java
// Why use finally?


public class OnOffSwitch { 
private static Switch sw = new Switch(); 
public static void f()
throws OnOffException1,OnOffException2 {}
public static void main(String[] args) { 
try { 
      sw.on();
// Code that can throw exceptions...
      f(); 
      sw.off();
    } catch(OnOffException1 e) {
      System.err.println("OnOffException1");
      sw.off();
    } catch(OnOffException2 e) {
      System.err.println("OnOffException2");
      sw.off();
    }
  }
} ///:~


程序的目的是要确保main( )结束的时候开关必须是关闭的,所以在每个try块和异常处
理程序的末尾都加入了对sw.off( )方法的调用。但也可能有这种情况:异常被抛出,但
没被处理程序捕获,这时sw.off( )就得不到调用。但是有了finally,你只要针对try块
把清理代码放在一处即可:


//: c09:WithFinally.java
// Finally Guarantees cleanup.


public class WithFinally { 
static Switch sw = new Switch();
public static void main(String[] args) { 
try { 
      sw.on();
// Code that can throw exceptions...
      OnOffSwitch.f();
    } catch(OnOffException1 e) {
      System.err.println("OnOffException1");

    } catch(OnOffException2 e) {

 System.err.println("OnOffException2");
    } finally {
      sw.off();
    }
  }
} ///:~


这里 sw.off( )被移到一处,并且保证在任何情况下都能得到执行。
 
甚至在异常没有被当前的异常处理程序捕获的情况下,异常处理机制也会在跳到更高一
层的异常处理程序之前,执行 finally 子句:


//: c09:AlwaysFinally.java
// Finally is always executed.
import com.bruceeckel.simpletest.*; 


class FourException extends Exception {} 


public class AlwaysFinally { 
private static Test monitor = new Test(); 
public static void main(String[] args) { 
    System.out.println("Entering first try block"); 
try { 
      System.out.println("Entering second try block"); 
try {
throw new FourException(); 
      } finally {
        System.out.println("finally in 2nd try block");
      }
    } catch(FourException e) {
      System.err.println( 
"Caught FourException in 1st try block"); 
    } finally {
      System.err.println("finally in 1st try block"); 
    }
    monitor.expect(new String[] { 
"Entering first try block",
"Entering second try block",
"finally in 2nd try block",
"Caught FourException in 1st try block",
"finally in 1st try block"
    });
  }
} ///:~

当涉及到break和continue语句的时候,finally子句也会得到执行。请注意,如果把
finally子句和带标记的break及continue配合使用,在Java里就没必要使用goto语句
了。


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值