天天看點

try-with-resources優先于try-finally

·一:代碼上的簡潔

使用Try-finally

static void copy(String src,String dst)throws IOException{

   InputString in = new FileInputStream(src);

try {

          OutputStream out = new FileOutStream(dst);

          try{

                byte[] buf = new byte[BUFFER_SIZE];

               int n;

              while((n = in.read(buf))>=0)

                     out.write(buf,0,n);

       }finally{

               out.close();       

      }

}finally{

in.close();

}

}

使用try-with-resources

static void copy(String src,String dst)throws IOException{

   try (InputString in = new FileInputStream(src);

          OutputStream out = new FileOutStream(dst)){

                byte[] buf = new byte[BUFFER_SIZE];

               int n;

              while((n = in.read(buf))>=0)

                     out.write(buf,0,n);

}

}

二:

static void firstLineOfFile(String path)throws IOException{

   BufferReader br= new BufferReader (new FileReader(path));

try{

        return br.readLine();

}finally{

     br.close();

}

在firstLineOfFile方法中,如果底層的實體裝置異常,那麼調用readLine就會出現異常,基于同樣·的原因,調用close也會出現異常。在這種情況下,第二個異常完全抹除了第一個異常。在異常堆軌迹中,完全沒有關于第一個異常的記錄,這在現實的系統中會導緻調試變得複雜,因為通常需要看到第一個異常才能診斷出問題所在。