Why is try-with-resources catch block selectively optional?

前端 未结 5 709
清酒与你
清酒与你 2021-02-02 08:43

I read that the catch block in try-with-resources is optional. I\'ve tried creating a Connection object in a try-with-resources block, with no subsequ

5条回答
  •  梦谈多话
    2021-02-02 09:09

    Not every Java class (!) throws an exception. Sometimes you just want to use a try-with-resources to use the auto-close feature, and nothing else.

    BufferedReader br = new BufferedReader(new FileReader(path));
    try {
        return br.readLine();
    } finally {
        if (br != null) br.close();
    }
    

    This the catch is optional because readLine() doesn't throw a (checked) exception.

    Yes, close() could throw an exception, but the try-with-resources handles that too.

    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    } 
    

    So this try-with-resources doesn't need a catch.

提交回复
热议问题