JDK7中引入了哪些与Java异常处理相关的更改?

自从引入Java 7 try-with资源以来。在这种情况下,我们在try块中声明一个或多个资源,这些资源在使用后将自动关闭。(在try块的末尾)

我们在try块中声明的资源应扩展java.lang.AutoCloseable类。

示例

以下程序演示了Java中的try-with-resources。

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) {
         ioe.printStackTrace();
      }
   }
}

输出结果

File copied successfully!!