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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值