不使用finally块释放资源
错误的写法:
- public void save(File f) throws IOException {
- OutputStream out = new BufferedOutputStream(new FileOutputStream(f));
- out.write(...);
- out.close();
- }
- public void load(File f) throws IOException {
- InputStream in = new BufferedInputStream(new FileInputStream(f));
- in.read(...);
- in.close();
- }
数据库访问也涉及到类似的情况:
- 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;
- }
数据库访问也涉及到类似的情况:
- 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;
- }