What changes has been introduced in JDK7 related to Exception handling in Java?

Java 8Object Oriented ProgrammingProgramming

Since Java 7 try-with resources was introduced. In this we declare one or more resources in the try block and these will be closed automatically after the use. (at the end of the try block)

The resources we declare in the try block should extend the java.lang.AutoCloseable class.


Following program demonstrates the try-with-resources in Java.

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopying {
   public static void main(String[] args) {
      try(FileInputStream inS = new FileInputStream(new File("E:\Test\sample.txt"));
      FileOutputStream outS = new FileOutputStream(new File("E:\Test\duplicate.txt"))){
         byte[] buffer = new byte[1024];
         int length;
         while ((length = inS.read(buffer)) > 0) {
            outS.write(buffer, 0, length);
         System.out.println("File copied successfully!!");
      } catch(IOException ioe) {


File copied successfully!!
Updated on 07-Aug-2019 09:17:57