Page 1 of 1

About Question enthuware.ocpjp.v8.2.1157 :

Posted: Fri Apr 07, 2023 2:02 pm
by oscarcito
Why is the write method called here before the close method and therefore does not throw an exception?

Code: Select all

public class Test {
    public static void main(String[] args) {
        try(PrintWriter bw = new PrintWriter("F:\\test.txt"))
        {
            bw.close();
            bw.write(1);
        } catch(IOException e) {
            System.out.println("IOException");
        }
    }
}

Re: About Question enthuware.ocpjp.v8.2.1157 :

Posted: Fri Apr 07, 2023 2:03 pm
by oscarcito
Are the resources closed at the end regardless of where they are located?

Re: About Question enthuware.ocpjp.v8.2.1157 :

Posted: Sun Apr 23, 2023 12:12 am
by admin
oscarcito wrote:
Fri Apr 07, 2023 2:03 pm
Are the resources closed at the end regardless of where they are located?
No, only the resources that are declared/defined in the try-with-resources clause are closed at the end of the try block automatically. If you create a resource instead a try block (instead of the try clause), that resource will not be closed automatically. In this code. bw is created in the try clause and so bw.close() will be invoked at the end of the try block automatically.

It is a different matter that there is an explicit call to bw.close in the try block also. This will be executed in the normal course of execution anyway.