什么是finally

finally块一般用来关闭物理资源(数据库连接,网络连接,磁盘文件等),这些物理资 源必须显式关闭。除非在try块、catch块中调用了退出虚拟机的方法 ( System.exit(0); ),否则不管在try块、catch块中执行怎样的代码,出现怎样的 情况,异常处理的finally块一定会被执行。

import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException;
/**  * finally关键字 finally块  * 
 * @author sxj  *  */ 
public class FinallyDemo {    
 public static void main(String[] args) {
        FileInputStream in = null;
 try {             
 	in = new FileInputStream("E:\\z\\BaseDataType.java");    
 	byte[] buf = new byte[1024];             
 	int count = 0;
            //!!此处故意写错,从而触发越界移除,演示finally块的作用!!  
    while ((count = in.read(buf, 0, buf.length)) >5) {
    System.out.println(new String(buf, 0, count));             
    }
   } catch (FileNotFoundException e) {
     //文件找不到异常             
     System.out.println("文件找不到异常"); 
     e.printStackTrace();         
   } catch (IOException e) {             
   //IO异常             
   System.out.println("IO异常");             
   e.printStackTrace();         
   } finally {             
   if (in != null) {                 
   try {                     
   in.close();                     
   System.out.println("finally块中 close()关闭IO流");                 
   } catch (IOException e) {                    
    e.printStackTrace();                
       }             
      }         
    }
  } 
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值