java 常见问题 之 不使用finally块释放资源

本文探讨了文件I/O操作和数据库访问中资源管理的重要性,并通过示例对比了正确与错误的资源关闭方式。强调了使用finally块确保资源被妥善关闭的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

不使用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. }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值