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

前端 未结 5 703
清酒与你
清酒与你 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:28

    You could just be throwing the exception up (or catching it in another try-catch block):

    private static void test() throws IOException {
        try(InputStream is = new FileInputStream("test.txt")) {
            while(is.read() > -1) {
            }
        } finally {
            // Will get executed, even if exception occurs
            System.out.println("Finished");
        }
    }
    

提交回复
热议问题