About Question enthuware.ocpjp.v8.2.1157 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
oscarcito
Posts: 4
Joined: Wed Jan 18, 2023 3:59 am
Contact:

About Question enthuware.ocpjp.v8.2.1157 :

Post 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");
        }
    }
}

oscarcito
Posts: 4
Joined: Wed Jan 18, 2023 3:59 am
Contact:

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

Post by oscarcito »

Are the resources closed at the end regardless of where they are located?

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: No registered users and 44 guests