java 常見問題 之 異常處理不徹底

異常處理不徹底

錯誤的寫法:

  1. try {   
  2. is = new FileInputStream(inFile);   
  3. os = new FileOutputStream(outFile);   
  4. finally {   
  5. try {   
  6. is.close();   
  7. os.close();   
  8. catch(IOException e) {   
  9. /* we can't do anything */   
  10. }   
  11. }  

is可能close失敗, 導致os沒有close

正確的寫法:

  1. try {   
  2. is = new FileInputStream(inFile);   
  3. os = new FileOutputStream(outFile);   
  4. finally {   
  5. try { 
  6. if (is != null) is.close(); } catch(IOException e) {/* we can't do anything */}   
  7. try {
  8.  if (os != null) os.close(); } catch(IOException e) {/* we can't do anything */}   
  9. }  

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

  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. }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章