異常處理不徹底
錯誤的寫法:
- try {
- is = new FileInputStream(inFile);
- os = new FileOutputStream(outFile);
- } finally {
- try {
- is.close();
- os.close();
- } catch(IOException e) {
- /* we can't do anything */
- }
- }
is可能close失敗, 導致os沒有close
正確的寫法:
- try {
- is = new FileInputStream(inFile);
- os = new FileOutputStream(outFile);
- } finally {
- try {
- if (is != null) is.close(); } catch(IOException e) {/* we can't do anything */}
- try {
- if (os != null) os.close(); } catch(IOException e) {/* we can't do anything */}
- }
數據庫訪問也涉及到類似的情況:
- Car getCar(DataSource ds, String plate) throws SQLException {
- Car car = null;
- Connection c = null;
- PreparedStatement s = null;
- ResultSet rs = null;
- try {
- c = ds.getConnection();
- s = c.prepareStatement("select make, color from cars where plate=?");
- s.setString(1, plate);
- rs = s.executeQuery();
- if (rs.next()) {
- car = new Car();
- car.make = rs.getString(1);
- car.color = rs.getString(2);
- }
- } finally {
- if (rs != null) try { rs.close(); } catch (SQLException e) { }
- if (s != null) try { s.close(); } catch (SQLException e) { }
- if (c != null) try { c.close(); } catch (SQLException e) { }
- }
- return car;
- }