简体   繁体   中英

Why declare Resource in try() while using try-with-resources

The try-with-resources Statement Following is example from Java Docs

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br =
                   new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}

As per doc ,

The try-with-resources statement ensures that each resource is closed at the end of the statement.

My question is, Why do I need to declare resource within parentheses immediately after the try keyword. (like BuffereReader above)

BuffereReader implements java.lang.AutoCloseable

So why not support something like this,

static String readFirstLineFromFile(String path) throws IOException {
        try{
            BufferedReader br =
                       new BufferedReader(new FileReader(path))
            return br.readLine();
        }
    }

And just implicitly close resource object once out of try. (As it has implemeted AutoCloseable)

I just had a thought, Why change in syntax.

Please Read Question Properly, Its Regarding Syntax Only.

In some situations you don't want to close immediately the AutoCloseable resource. For example:

static BufferedReader getBufferedReader(String path) {
    try{
        FileReader fr = new FileReader(path);
        return new BufferedReader(fr);
    }
    catch(IOException ex) {
        // handle somehow
    }
}

In this case you cannot close the fr upon the exit of the try block. Otherwise the returned BufferedReader will be invalid. So you should explicitly specify when you want to close the resource. That's why special syntax was invented.

Because it would change the semantics of existing program. A new syntax was needed for this new feature.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM