zoukankan      html  css  js  c++  java
  • Java: AutoCloseable接口

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

    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. // JDK1.7以前的版本,释放资源的写法
    15. static String readFirstLingFromFile(String path) throws IOException {
    16. BufferedReader br = null;
    17. try {
    18. br = new BufferedReader(new FileReader(path));
    19. return br.readLine();
    20. } catch (IOException e) {
    21. e.printStackTrace();
    22. } finally {
    23. if (br != null)
    24. br.close();
    25. }
    26. return null;
    27. }
    28. // JDK1.7中的写法,利用AutoCloseable接口
    29. // 代码更精练、完全
    30. static String readFirstLineFromFile(String path) throws IOException {
    31. try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    32. return br.readLine();
    33. }
    34. }
    35. }
    36. class Resource implements AutoCloseable {
    37. void doSome() {
    38. System.out.println("do something");
    39. }
    40. @Override
    41. public void close() throws Exception {
    42. System.out.println("resource closed");
    43. }
    44. }
    45. class ResourceOther implements AutoCloseable {
    46. void doSome() {
    47. System.out.println("do something other");
    48. }
    49. @Override
    50. public void close() throws Exception {
    51. System.out.println("other resource closed");
    52. }
    53. }
  • 相关阅读:
    HTTP
    spark-architecture
    SPARK SQL
    《算法:第四版》课后练习 1.1 答案
    随机生成六位不重复数值
    【转】策略与机制分离
    【转】Linux内核源码分析方法
    【转】机制与策略
    软件工程中的现代方法
    编码通用缩写表
  • 原文地址:https://www.cnblogs.com/dengyungao/p/7525090.html
Copyright © 2011-2022 走看看