8.3 Close应该放在finally块里面吗?

有三种不同的方式关闭输出写入器。第一种将close()语句放在try子句方法里面,第一种在try子句中放置close()方法,第二个放在finally子句中,第三个使用try-with-resources语句,哪个是最正确?

//close() is in try clause
try {
    PrintWriter out = new PrintWriter(
            new BufferedWriter(
            new FileWriter("out.txt", true)));
    out.println("the text");
    out.close();
} catch (IOException e) {
    e.printStackTrace();
}

close 放在finally里面。

//close() is in finally clause
PrintWriter out = null;
try {
    out = new PrintWriter(
        new BufferedWriter(
        new FileWriter("out.txt", true)));
    out.println("the text");
} catch (IOException e) {
    e.printStackTrace();
} finally {
    if (out != null) {
        out.close();
    }
}
//try-with-resource statement
try (PrintWriter out2 = new PrintWriter(
            new BufferedWriter(
            new FileWriter("out.txt", true)))) {
    out2.println("the text");
} catch (IOException e) {
    e.printStackTrace();
}

答案

因为Writer必须在任何情况下被关闭(异常情况或非异常情况),close()应该在finally被关闭。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,664评论 0 4
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,982评论 19 139
  • 日期和时间 如何取得年月日、小时分钟秒?创建java.util.Calendar 实例,调用其get()方法传入不...
    wangxiaoda阅读 261评论 0 0
  • 愿为西南塞上风,几时何哭盈认,悲其迎秋染霜尘。 愿为冬笙箜篌引,静水流深棋琴,悲其快意江山临。 愿为凤冠红烛泪,曲...
    莘九阅读 146评论 0 0
  • 思思,今天我们单独在一起的时间不多,最开心的事情莫过于晚上一起涂指甲油。人生有很多第一次,我真的好希望跟你一块去经...
    思思与努努阅读 114评论 0 0