Java try-with-resources
we use try catch
as follows:
try { // Some code that may generate exception }
catch(Exception ex) { //handle exception }
finally { //close any open resources etc. }
But sometime you might come across a code where parentheses ( ) is used right after try .
try (resource declaration) {
// use of the resource
} catch (ExceptionType e1) {
// handle exception
}
The above example is try-with-resources statement introduced in java 1.7.
What is a Resource?
A resource can be thought of as something controlled by the operating system, a file, byte array, buffered reader or a socket for example, that can be accessed and borrowed by a program.
It is important for the program that accesses the resource to return it to the operating system once it has finished using it.
An Object that implements the AutoCloseable interface holds on to a resource until it is done using it within a try block and then it is automatically closed.
Whereas an object that implements a Closeable interface can be closed by calling .close().
Both AutoCloseable and Closeable only include one abstract method close() which closes a resource and releases any underlying resources associated with it.
The try-with-resources statement closes all the resources that implement the AutoCloseable interface.
Example 1 : Resource — Buffered Reader
import java.io.*;class Main {
public static void main(String[] args) {
String line;
try(BufferedReader br = new BufferedReader(new FileReader(“test.txt”))) {
while ((line = br.readLine()) != null) {
System.out.println(“Line =>”+line);
}
} catch (IOException e) {
System.out.println(“IOException in try block =>” + e.getMessage());
}
}
}
Suppressed Exception
If exceptions are thrown from both the try block and the try-with-resources statement, exception from the try block is thrown and exception from the try-with-resources statement is suppressed.
The suppressed exceptions can be retrieved by calling the Throwable.getSuppressed() method from the exception thrown by the try block. This method returns an array of all suppressed exceptions.
catch(IOException e) {
System.out.println("Thrown exception=>" + e.getMessage());
Throwable[] suppressedExceptions = e.getSuppressed();
for (int i=0; i<suppressedExceptions.length; i++) {
System.out.println("Suppressed exception=>" + suppressedExceptions[i]);
}
}
Example 2: Resource — Connection
public User findByFirstName(String firstName){
User user =new User();
try (Connection connection = dataSource.getConnection()) {
PreparedStatement selectStatement = connection.prepareStatement("select * from users where first_name = ?");
selectStatement.setString(1, firstName);
ResultSet rs = selectStatement.executeQuery();
if (rs.next()) { user = extractUserFromResultSet(rs);}
}
catch (SQLException se) {
System.out.println(se.getMessage());
}
return user;
}
Advantages of using try-with-resources
- finally block not required to close the resource
- . We can declare more than one resource in the try-with-resources statement by separating them with a semicolon ;
try ( Scanner scanner = new Scanner(new File(“testRead.txt”));
PrintWriter writer = new PrintWriter(new File(“testWrite.txt”))) {
while (scanner.hasNext()) {
writer.print(scanner.nextLine());
}
}
3. The reference of the resource can be used even if it is not declared locally. (Java 9)
Scanner scanner = new Scanner(new File(“testRead.txt”));
try (scanner) {
// code
}
Credits :
1. https://medium.com/@priya104/the-autocloseable-interface-404ce6edee85
2. https://www.programiz.com/java-programming/try-with-resources
3. https://stackoverflow.com/questions/37583464/what-is-round-brackets-parentheses-in-try-catch-in-java