Chinaunix首页 | 论坛 | 博客
  • 博客访问: 686312
  • 博文数量: 152
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 1793
  • 用 户 组: 普通用户
  • 注册时间: 2013-09-12 12:26
个人简介

相信自己,只有不想做的,没有做不到的。

文章分类

全部博文(152)

文章存档

2021年(1)

2015年(2)

2014年(74)

2013年(75)

分类: Java

2014-08-11 22:19:56

目标:掌握在使用try-catch 来捕捉异常的时候,使用finally从句来清理资源。

源文件:CatchException.java
/*
 * 使用try-catch-finally捕捉异常
 * author guojing
 * e-mail guo443193911@126.com
 */


package cn.com.ExceptionExam;


import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


public class ExceptionExam {


/**
* @param args
* @throws FileNotFoundException 
*/
public static void main(String[] args) throws FileNotFoundException {
// TODO Auto-generated method stub
FileInputStream fis = null;


try {
fis = new FileInputStream("c:/a.txt");
int b;
b = fis.read();


while(b != -1){
System.out.println(b);
b = fis.read();
}

// fis.close();
} catch (FileNotFoundException e) {
// TODO: handle exception
System.out.println("FileNotFoundException");
}catch(IOException e1){
System.out.println("IOException");
}finally{

try {
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("文件关闭出错");
            }
        }
    }
}

文件c:/a.txt的内容为: asdasdasd

编译运行程序的结果为:
a
s
d
a
s
d
a
s
d
所以打印以上结果,在这个程序中,在finally从句中对需要清理的资源进行了处理。
因为finally一定会被执行到,所以这是一种比较理想的进行清理操作的方式。



阅读(468) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~