Java: AutoCloseable接口

K7 增加了一些新特性,其中报错AutoCloseable 等。新特性包括如下,下面主要说说AutoCloseable 。

21140109_fDgg.jpg

JDK7 中只要实现了AutoCloseable 或Closeable 接口的类或接口,都可以使用try-with-resource 来实现异常处理和资源关闭异常抛出顺序。

Java se 7 中的try-with-resource 机制中异常的抛出顺序与Java se 7 以前的版本有一点不一样。是先声明的资源后关闭,JDK7 之前的版本中,如果rd.readLine() 与rd.close()(在finally块中) 都抛出异常则只会抛出 finally  块中的异常,不会抛出rd.readLine(); 中的异常。这样经常会导致得到的异常信息不是调用程序想要得到的。

JDK7 及以后版本中如果采用try-with-resource 机制,如果在try-with-resource 声明中抛出异常(可能是文件无法打开或无法关闭)同时rd.readLine(),若抛出异常,则只会抛出rd.readLine() 的异常。

 
  1. public class AutoCloseableTest {
  2. // 声明资源时要分析好资源关闭顺序,先声明的后关闭
  3. // 在try-with-resource中也可以有catch与finally块。
  4. // 只是catch与finally块是在处理完try-with-resource后才会执行。
  5. public static void main(String[] args) {
  6. try (Resource res = new Resource();
  7. ResourceOther resOther = new ResourceOther();) {
  8. res.doSome();
  9. resOther.doSome();
  10. } catch (Exception ex) {
  11. ex.printStackTrace();
  12. }
  13. }
  14.  
  15. // JDK1.7以前的版本,释放资源的写法
  16. static String readFirstLingFromFile(String path) throws IOException {
  17. BufferedReader br = null;
  18. try {
  19. br = new BufferedReader(new FileReader(path));
  20. return br.readLine();
  21. } catch (IOException e) {
  22. e.printStackTrace();
  23. } finally {
  24. if (br != null)
  25. br.close();
  26. }
  27. return null;
  28. }
  29.  
  30. // JDK1.7中的写法,利用AutoCloseable接口
  31. // 代码更精练、完全
  32. static String readFirstLineFromFile(String path) throws IOException {
  33. try (BufferedReader br = new BufferedReader(new FileReader(path))) {
  34. return br.readLine();
  35. }
  36. }
  37. }
  38. class Resource implements AutoCloseable {
  39. void doSome() {
  40. System.out.println("do something");
  41. }
  42. @Override
  43. public void close() throws Exception {
  44. System.out.println("resource closed");
  45. }
  46. }
  47. class ResourceOther implements AutoCloseable {
  48. void doSome() {
  49. System.out.println("do something other");
  50. }
  51. @Override
  52. public void close() throws Exception {
  53. System.out.println("other resource closed");
  54. }
  55. }

转载于:https://my.oschina.net/u/3624220/blog/1517946

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值