Reputation: 10082
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.
Upvotes: 3
Views: 4041
Reputation: 310869
Because it would change the semantics of existing program. A new syntax was needed for this new feature.
Upvotes: 4
Reputation: 100169
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.
Upvotes: 8