日期:2014-05-20  浏览次数:20945 次

为什么把关闭资源放finally中, 放在try-catch之后不可以么?
1.第一种写法。

BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

2.第二种写法。

BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
bos.close();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();


3.第三种写法。

BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream("d:/123.txt"));
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();

try {
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

请问哪种更好一些,为什么?

------解决方案--------------------
第一种最好,finally块会保证执行,即使没有catch到相应的异常。
第二种情况出现异常,就无法关闭了。
第三种情况如果不是FileNotFoundException,那么之后的close语句也不会执行。