首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >try catch vs try-with-resources

try catch vs try-with-resources
EN

Stack Overflow用户
提问于 2019-06-13 09:47:39
回答 1查看 58关注 0票数 2

为什么在readFile2()中我需要捕获FileNotFoundException,然后是close()方法抛出的IOException,而在try-with-resources(inside readfile1)中Java没有要求我处理FileNotFoundException,这是怎么回事?

代码语言:javascript
复制
public class TryWithResourcesTest {

    public static void main(String[] args) {

    }

    public static void readFile1() {
        try(Reader reader = new BufferedReader(new FileReader("text.txt"))) {
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readFile2() {
        Reader reader = null;
        try {
            reader = new BufferedReader(new FileReader("text.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if(reader != null)
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-06-13 09:49:42

FileNotFoundExceptionIOException的一个子类。通过捕捉后者,你也可以捕捉到前者。它与try-catch和try- with -resources没有任何关系。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56572337

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档