Java try with resources full explanation with Examples

Java try with resources

 196 total views

Java 7 introduces Java Try with Resources as an upgrade of the Normal try-catch block with several extra features.

It was introduced by Oracle to implement Automatic resource management to effectively manage the closure and usage of resources.

What is a resource?

As I have already mentioned in one of my previous blogs on the eclipse resource folder, A resource is an entity that a Java Program uses to achieve a certain task.

For Example, An Image file, A Database, A Web Page, and etc.

Java uses several Classes and their instances to access these resources For instance-

To read files we use java.io.FilterInputStream

We connect to the database using java.sql.Connection

To communicate with server objects we use java.net.Socket

Java developers frequently use all the above classes to access one or another resource.

Its the responsibility of the developer to close the channel established by these classes to access the resource.

Java try-with-resources explanation

Any Class that implements the java.lang.AutoCloseable interface can be used in the Try-with-resource construct.

Below is a code example in layman’s term

try (Open The Resource){
		    perform resource based operation
		} catch (Exception ex) {
		    If raised, Handle the exception
		}

Try-catch-finally vs Try-with-resources

In this tutorial, I will use Java Try with resources JDBC example to explain and highlight the difference.

public static void main(String[] args) {
		Connection dbConnection = null;
		String lURL =
				"jdbc:mysql://localhost:3306/testDB";
		String lUser =
				"root";
		String lPassword =
				"root";
		try {
			dbConnection =
					DriverManager
					.getConnection(lURL, lUser, lPassword);
			System.out.println("DB Connection Success");
		} catch (SQLException ex) {
			System.out.println("Exception occured");
			ex.printStackTrace();
		} finally {
			if (dbConnection != null) {
				try {
					dbConnection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}
	}
public static void main(String[] args) {
		
        String lURL =
				"jdbc:mysql://localhost:3306/testDB";
		String lUser =
				"root";
		String lPassword =
				"root";
		try (Connection dbConnection
				= DriverManager
				.getConnection(lURL, lUser, lPassword))
		{
		    System.out.println("DB Connection Success");
		} catch (SQLException ex) {
		    System.out.println("Exception occured");
		    ex.printStackTrace();
		}
	}

Two Major points to Notice in above code comaprison

  1. In try-with-resources, inline initialization of Connection object.
  2. Removal of Finally block because of automatic Connection closure.

Handling multiple resources in a try-with-resources block

Suppose you want to access two resources from your method.

Do you need to write two try-with-resources block?

The Answer is NO.

You can handle two or more resources from a single try-with-resources construct For Example

UseCase – Read a CSV file and save its data into DB

In this example we will access two resources “User.csv” and “testDB”.

Now lets look into the code How can we achieve it

public static void main(String[] args) {
		String csvFileURL = "/techdora/csv/User.csv";
		String lURL =
				"jdbc:mysql://localhost:3306/testDB";
		String lUser =
				"root";
		String lPassword =
				"root";
		try (Scanner scanner = new Scanner(new File(csvFileURL));
				Connection dbConnection= DriverManager.getConnection(lURL, lUser, lPassword))
		{
			// Read CSV File
			// Process and Save Data in Database
		} catch (SQLException ex) {
		    System.out.println("SQLException occured");
		    ex.printStackTrace();
		}
		catch (FileNotFoundException ex) {
		    System.out.println("FileNotFoundException occured");
		    ex.printStackTrace();
		}
	}

In the above example, the try construct is accessing two Resources – CSV file and Database.

Order of resource closure

The resources that are initiated first will be closed last.

Therefore the chronology in the above code will be

  1. Scanner Class acquires the CSV file.
  2. Connection class created a DB connection.
  3. Execution of Try block’s code
  4. The connection class releases a DB connection.
  5. The scanner class releases the CSV file.

Benefits of Java try with resources

Introduction of Java Try-with-resources is mainly for automatic closure of resources hence its benefits relate to it only.

  1. Automatic Java resource closure.
  2. Removal of finally block, if required only for resource closure.
  3. Automatic closing the resource will lead to fewer memory leaks issue.
  4. The more relevant exception is propagated up the Call stack For Example if an Exception occurs in try-block also one exception occurs while resource closure. The Exception from try-block will be propagated.
  5. Multiple resource handling from single try-with-resource.
  6. Additionally, it leads to reduced and more readable Code Structure.

Java try with resources Catch and Finally block

The catch and finally block still work in the same way as they use to work with Try-Catch-finally.

Firstly, If the Catch block is present, it will catch the exception.

Secondly, On removal of the Catch block, the method signature must have the throws clause.

Thirdly, If the Finally block is present, except resource closure any other task can be executed.

Conclusion

In Conclusion, I will say the industry is moving towards automation and these kind of small changes can lead to better performance and resource handling.

Leave a Reply

Your email address will not be published. Required fields are marked *