java 常見問題 之 不使用finally塊釋放資源

不使用finally塊釋放資源

錯誤的寫法:

  1. public void save(File f) throws IOException {   
  2. OutputStream out = new BufferedOutputStream(new FileOutputStream(f));   
  3. out.write(...);   
  4. out.close();   
  5. }   
  6. public void load(File f) throws IOException {   
  7. InputStream in = new BufferedInputStream(new FileInputStream(f));   
  8. in.read(...);   
  9. in.close();   
  10. }  

數據庫訪問也涉及到類似的情況:

  1. Car getCar(DataSource ds, String plate) throws SQLException {   
  2. Car car = null;   
  3. Connection c = null;   
  4. PreparedStatement s = null;   
  5. ResultSet rs = null;   
  6. try {   
  7. c = ds.getConnection();   
  8. s = c.prepareStatement("select make, color from cars where plate=?");   
  9. s.setString(1, plate);   
  10. rs = s.executeQuery();   
  11. if (rs.next()) {   
  12. car = new Car();   
  13. car.make = rs.getString(1);   
  14. car.color = rs.getString(2);   
  15. }   
  16. finally {   
  17. if (rs != nulltry { rs.close(); } catch (SQLException e) { }   
  18. if (s != nulltry { s.close(); } catch (SQLException e) { }   
  19. if (c != nulltry { c.close(); } catch (SQLException e) { }   
  20. }   
  21. return car;   
  22. }  

數據庫訪問也涉及到類似的情況:

  1. Car getCar(DataSource ds, String plate) throws SQLException {   
  2. Car car = null;   
  3. Connection c = null;   
  4. PreparedStatement s = null;   
  5. ResultSet rs = null;   
  6. try {   
  7. c = ds.getConnection();   
  8. s = c.prepareStatement("select make, color from cars where plate=?");   
  9. s.setString(1, plate);   
  10. rs = s.executeQuery();   
  11. if (rs.next()) {   
  12. car = new Car();   
  13. car.make = rs.getString(1);   
  14. car.color = rs.getString(2);   
  15. }   
  16. finally {   
  17. if (rs != nulltry { rs.close(); } catch (SQLException e) { }   
  18. if (s != nulltry { s.close(); } catch (SQLException e) { }   
  19. if (c != nulltry { c.close(); } catch (SQLException e) { }   
  20. }   
  21. return car;   
  22. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章