JDK1.7中新增自动释放资源接口AutoCloseable

新增了try-with-resource 异常声明 java

在JDK7中只要实现了AutoCloseable或Closeable接口的类或接口,均可以使用try-with-resource来实现异常处理和资源关闭 ide

异常抛出顺序。在Java se 7中的try-with-resource机制中异常的抛出顺序与Java se 7之前的版本有一点不同。spa

是先声明的资源后关闭code

JDK7之前若是rd.readLine()与rd.close()(在finally块中)都抛出异常则只会抛出finally块中的异常,不会抛出rd.readLine();中的异常。这样常常会致使获得的异常信息不是调用程序想要获得的。接口

JDK7及之后版本中若是采用try-with-resource机制,若是在try-with-resource声明中抛出异(多是文件没法打或都文件没法关闭)同时rd.readLine();也势出异常,则只会势出rd.readLine()的异常。资源

public class Main {
 //声明资源时要分析好资源关闭顺序,先声明的后关闭
 //在try-with-resource中也能够有catch与finally块。
 //只是catch与finally块是在处理完try-with-resource后才会执行。
 public static void main(String[] args) {
  try (Resource res = new Resource();
    ResourceOther resOther = new ResourceOther();) {
   res.doSome();
   resOther.doSome();
  } catch (Exception ex) {
   ex.printStackTrace();
  }
 }
 //JDK1.7之前的版本,释放资源的写法
 static String readFirstLingFromFile(String path) throws IOException {
  BufferedReader br = null;
  try {
   br = new BufferedReader(new FileReader(path));
   return br.readLine();
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (br != null)
    br.close();
  }
  return null;
 }
 //JDK1.7中的写法,利用AutoCloseable接口
 //代码更精练、彻底
 static String readFirstLineFromFile(String path) throws IOException {
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
   return br.readLine();
  }
 }
}
class Resource implements AutoCloseable {
 void doSome() {
  System.out.println("do something");
 }
 @Override
 public void close() throws Exception {
  System.out.println("resource closed");
 }
}
class ResourceOther implements AutoCloseable {
 void doSome() {
  System.out.println("do something other");
 }
 @Override
 public void close() throws Exception {
  System.out.println("other resource closed");
 }
}
相关文章
相关标签/搜索