The try-with-resources statement ensures that each resource is closed
at the end of the statement.
Otherwords, in try-with-resources statement any
at the end of the statement.
Otherwords, in try-with-resources statement any
catch
or finally
block is run after the resources declared have been closed.*Resource - is an object that must be closed after the program is finished with it.
Closing a stream when it's no longer needed is very important to avoid serious resource leaks.
Use
Use
try-with-resources
or close those in finally
block to guarantee
that both streams will be closed even if an error occurs.
private void readWithout() {
// regular approach
try {
FileInputStream input = new FileInputStream("file.dat");
int c;
while ((c = in.read()) != -1) {
System.out.println(byteValue + " ");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null)
{
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private void readWith() {
// try-with-resources approach
try (FileInputStream input = new FileInputStream("file.dat")) {
int c;
while ((c = in.read()) != -1) {
System.out.println(byteValue + " ");
}
} catch (IOException) {
e.printStackTrace();
}
}
In the
try-with-resources
statement, the resources are closed in the reverse order of their declaration.
try (Connection conn = DriverManager.getConnection(url, user, pwd);
Statement stmt = conn.createStatement()) {
/*Execute query*/
} //note: no catch or finally here
So stmt.close()
will be called first, followed by conn.close()
.If there is an exception thrown from the
try
block,
the exception will be caught by the catch
statement as usually,
but as we know resources are closed before the catch
or finally
invocations.
So,any exceptions thrown as a result of closing resources at the end of the
try
block are suppressed if there was also an exception thrown in the try
block.
These exceptions can be retrieved from the exception thrown by calling the getSuppressed()
method on the exception thrown.
For example:
} catch (SQLException se) {
out.println("SQLException: " + se);
// Get an array of suppressed exceptions
Throwable[] suppressed = se.getSuppressed();
for (Throwable t: suppressed) {
out.println("Suppressed exception: " + t);
}
No comments:
Post a Comment