๐ŸŽ‰ Special Offer !    Code: GET300OFF    Flat โ‚น300 OFF on every Java Course
Grab Deal ๐Ÿš€

Try-With-Resource in Java Exception Handling  


Introduction

  • In previous topics, we have learned about the finally block which is used to execute cleanup code and release resources like files, database connections, or network streams.
  • But managing resources manually can be error-prone and lead to resource leaks if not handled properly.
  • Also we have write a lot of boilerplate code to ensure resources are closed properly.
  • To address these issues, Java 7 introduced the try-with-resources.
  • Definition:
    • Try-With-Resources is a feature introduced in Java 7 that allows you to declare resources in the try statement.
    • These resources are automatically closed at the end of the try block, eliminating the need for a finally block for cleanup.
      • A resource is any object that implements the AutoCloseable or Closeable interface (like FileInputStream, BufferedReader, Scanner, Connection etc.).
  • Use:
    • Automatically closes resources after use, avoiding resource leaks.
    • Reduces boilerplate code, no need for explicit finally blocks for closing.
    • Makes code cleaner, safer and more readable.
    • Ensures exception-safe resource management, even if exceptions occur in the try block.
  • Syntax:
    • try (ResourceType resource = new ResourceType())
      {
          // use the resource
      } 
      catch (ExceptionClassType e)
      {
          // handle exception
      }
    • Multiple resources can be declared using semicolon ; separation
      try ( ResourceType1 res1 = new ResourceType1();
             ResourceType2 res2 = new ResourceType2() )
      {
          // use resources
      }
      catch (ExceptionClassType e)
      {
          // handle exception
      }
  • Example:
    • import java.io.BufferedReader;
      import java.io.FileReader;
      import java.io.IOException;
      
      public class TryWithResourcesDemo
      {
          public static void main(String[] args)
          {
              System.out.println("----- App Started -----");
      
              // try-with-resources automatically closes BufferedReader
              try (BufferedReader br = new BufferedReader(new FileReader("test.txt")))
              {
                  String line;
                  while ((line = br.readLine()) != null)
                  {
                      System.out.println(line);
                  }
              } 
              catch (IOException e)
              {
                  System.out.println("IOException occurred: " + e);
              }
      
              System.out.println("----- App Finished Successfully -----");
          }
      }

Points to remember for Try-With-Resource block:
  1. No need for explicit finally block to close the resource.
  2. Resources must implement AutoCloseable or Closeable.
  3. Multiple resources can be managed in a single try statement.
  4. Exceptions during resource closing are suppressed but can be retrieved using Throwable.getSuppressed().