AutoCloseable
is introduced.And resoureces like Connection ,BufferedReader and BufferedWriter etc extends AutoCloseable. The
try
-with-resources statement is a try
statement that declares one or more resources. The try
-with-resources statement ensures that each resource is closed at the end of the try statement. Any object that implements java.lang.AutoCloseable
, can be used as a resource inside the try
-with-resources statement.The following example writes a line in a file. It uses an instance of
BufferedWriter
to write data in the file. BufferedWriter
is a resource that must be closed after the program is finished with it:static String writeALineToFile(String path) throws IOException {
try (BufferedWriter bw =
new BufferedWriter(new FileWriter(new File("path")))) {
return bw.write();
}
}
try
-with-resources statement is a BufferedWriter
. The declaration statement appears within parentheses immediately after the try
keyword. The class BufferedWriter
, in Java SE 7 and later, implements the interface java.lang.AutoCloseable
. Because the BufferedWriter
instance is declared in a try
-with-resource statement, it will be closed regardless of whether the try
statement completes normally or abruptly (as a result of the method BufferedWriter
.write
throwing an IOException
).Let's make it clear that here try-with-resource statement and try block are two different things.
Prior to Java SE 7, we can use a
finally
block to ensure that a resource is closed regardless of whether the try
statement completes normally or abruptly. The following example uses a finally
block instead of a try
-with-resources statement:static String writeALineToFileWithFinally(String path)
throws IOException {
try {
BufferedWriter bw =
new BufferedWriter(new FileWriter(new File("path")))) ;
bw.write();
}
}
} finally {
if (bw != null) bw.close();
}
}
write
and close
both throw exceptions, then the method writeALineToFileWithFinally
throws the exception thrown from the finally
block; the exception thrown from the try
block is suppressed.But In contrast, in the example
readFirstLineFromFile
, if exceptions are thrown from both the try
block and the try
-with-resources statement, then the method readFirstLineFromFile
throws the exception thrown from the try
block; the exception thrown from the try
-with-resources block is suppressed.We can retrieve the suppressed exceptions by calling the
Throwable.getSuppressed
method from the exception thrown by the try
block.Note: A
try
-with-resources statement can have catch
and finally
blocks just like an ordinary try
statement. In a try
-with-resources statement, any catch
or finally
block is run after the resources declared have been closed.