- Mastering Java 11
- Dr. Edward Lavieri
- 234字
- 2021-08-13 15:43:24
The try-with-resource statement
The try-with-resource statement previously required a new variable to be declared for each resource in the statement when a final variable was used. Here is the syntax for the try-with-resource statement prior to Java 9 (in Java 7 or 8):
try ( // open resources ) {
// use resources
} catch (// error) {
// handle exceptions
}
// automatically close resources
Here is a code snippet using the preceding syntax:
try ( Scanner xmlScanner = new Scanner(new File(xmlFile)); {
while (xmlScanner.hasNext()) {
// read the xml document and perform needed operations
}
xmlScanner.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Your XML file was not found.");
}
Since Java 9, the try-with-resource statement can manage final variables without requiring a new variable declaration. So, we can now rewrite the earlier code in Java 9, 10, or 11, as shown here:
Scanner xmlScanner = new Scanner(newFile(xmlFile));
try ( while (xmlScanner.hasNext()) {
{
// read the xml document and perform needed operations
}
xmlScanner.close();
} catch (FileNotFoundException fnfe) {
System.out.println("Your XML file was not found.");
}
As you can see, the xmlScanner object reference is contained inside the try-with-resource statement block, which provides for automatic resource management. The resource will automatically be closed as soon as the try-with-resource statement block is exited.
You can also use a finally block as part of the try-with-resource statement.