JDK1.7中新增自動釋放資源接口AutoCloseable

新增了try-with-resource 異常聲明java

在JDK7中只要實現了AutoCloseable或Closeable接口的類或接口,均可以使用try-with-resource來實現異常處理和資源關閉web

異常拋出順序。在Java se 7中的try-with-resource機制中異常的拋出順序與Java se 7之前的版本有一點不同。ide

是先聲明的資源後關閉spa

JDK7之前若是rd.readLine()與rd.close()(在finally塊中)都拋出異常則只會拋出finally塊中的異常,不會拋出rd.readLine();中的異常。這樣常常會致使獲得的異常信息不是調用程序想要獲得的。code

JDK7及之後版本中若是採用try-with-resource機制,若是在try-with-resource聲明中拋出異(多是文件沒法打或都文件沒法關閉)同時rd.readLine();也勢出異常,則只會勢出rd.readLine()的異常。orm

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");
 }
}
相關文章
相關標籤/搜索