• try with resources详解


    https://blog.csdn.net/tianzhonghaoqing/article/details/118720380

    概述
    try-with-resources自JDK7引入,在JDK9中进行了改进,使得用户可以更加方便、简洁的使用try-with-resources。

    JDK7之前资源需要手动关闭
    下面是一个常见的文件资源关闭的示例:

    BufferedWriter writer = null;
    try {
        writer = Files.newBufferedWriter(file, charset);
        writer.write(s, 0, s.length());
    } catch (IOException x) {
        System.err.format("IOException: %s%n", x);
    } finally {
        if (writer != null) writer.close();
    }


    因此在JDK7之前,必须要牢记在finally中执行关闭资源的方法,否则随着程序不断运行,资源泄露将会累计成重大的生产事故,然而如果你同时打开多个资源,那么将会出现噩梦般的场景。

    public class Demo {
        public static void main(String[] args) {
            BufferedInputStream bin = null;
            BufferedOutputStream bout = null;
            try {
                bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
                bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")));
                int b;
                while ((b = bin.read()) != -1) {
                    bout.write(b);
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
            finally {
                if (bin != null) {
                    try {
                        bin.close();
                    }
                    catch (IOException e) {
                        e.printStackTrace();
                    }
                    finally {
                        if (bout != null) {
                            try {
                                bout.close();
                            }
                            catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }


    关闭资源的代码竟然比业务代码还要多!!!这是因为,我们不仅需要关闭BufferedInputStream,还需要保证如果关闭BufferedInputStream时出现了异常, BufferedOutputStream也要能被正确地关闭。所以我们不得不借助finally中嵌套finally大法。可以想到,打开的资源越多,finally中嵌套的将会越深!!!

    JDK7使用try-with-resources语法糖
    我们可以利用Java 1.7中新增的try-with-resource语法糖来打开资源,而无需码农们自己书写资源来关闭代码。

    public class TryWithResource {
    
        public static void main(String[] args) {
            try (BufferedInputStream bin = new BufferedInputStream(new FileInputStream(new File("test.txt")));
                 BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(new File("out.txt")))) {
                int b;
                while ((b = bin.read()) != -1) {
                    bout.write(b);
                }
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

     
    try-with-resources详解
    try-with-resources 是 JDK 7 中一个新的异常处理机制,它能够很容易地关闭在 try-catch 语句块中使用的资源。所谓的资源(resource)是指在程序完成后,必须关闭的对象。try-with-resources 语句确保了每个资源在语句结束时关闭。所有实现了 java.lang.AutoCloseable 接口(其中,它包括实现了 java.io.Closeable 的所有对象),可以使用作为资源。
    关闭单一资源示例 :

    public class Demo {    
        public static void main(String[] args) {
            try(Resource res = new Resource()) {
                res.doSome();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    class Resource implements AutoCloseable {
        void doSome() {
            System.out.println("do something");
        }
        @Override
        public void close() throws Exception {
            System.out.println("resource is closed");
        }
    }

    输出结果:

    do something
    resource is closed
     
    关闭多个资源示例 

    public class Main2 {    
        public static void main(String[] args) {
            try(ResourceSome some = new ResourceSome();
                 ResourceOther other = new ResourceOther()) {
                some.doSome();
                other.doOther();
            } catch(Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    class ResourceSome implements AutoCloseable {
        void doSome() {
            System.out.println("do something");
        }
        @Override
        public void close() throws Exception {
            System.out.println("some resource is closed");
        }
    }
    
    class ResourceOther implements AutoCloseable {
        void doOther() {
            System.out.println("do other things");
        }
        @Override
        public void close() throws Exception {
            System.out.println("other resource is closed");
        }
    }

    输出结果:

    do something
    do other things
    other resource is closed
    some resource is closed
     
    ==可以看到在 try 语句中越是最后使用的资源,越是最早被关闭。 ==

    try-with-resources异常处理机制:

        private static void testAutoClose() {
            AutoCloseable global_obj1 = null;
            AutoCloseable global_obj2 = null;
            try(AutoCloseable obj1 = new AutoClosedImpl("obj1");
                AutoCloseable obj2 = new AutoClosedImpl("obj2");){
                global_obj1= obj1;
                int i = 1/0;
                global_obj2= obj2;
            } catch (Exception e) {
                e.printStackTrace();
            }finally{
                try{
                    System.out.println("before finally close");
                    if(global_obj1!=null){
                        global_obj1.close();
                    }
                    if(global_obj2!=null){
                        global_obj2.close();
                    }
                    System.out.println("after finally close");
                }   catch(Exception e){
                    e.printStackTrace();
                }
            }
        }
     
        private static class AutoClosedImpl implements AutoCloseable{
            private String name;
            public AutoClosedImpl(String name){
                this.name = name;
            }
            @Override
            public void close() throws Exception {
                System.out.println(name+" closing");
            }
        }

    执行testAutoClose()方法,会打印出如下结果:

    obj2 closing
    obj1 closing
    before finally close
    obj1 closing
    after finally close
    java.lang.ArithmeticException: / by zero
    at trywithresources.AutoCloseTest.testAutoClose(AutoCloseTest.java:60)
    at trywithresources.AutoCloseTest.main(AutoCloseTest.java:12)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
     
    处理规则
    凡是实现了AutoCloseable接口的类,在try()里声明该类实例的时候,在try结束后,close方法都会被调用
    try结束后自动调用的close方法,这个动作会早于finally里调用的方法。
    不管是否出现异常(int i=1/0会抛出异常),try()里的实例都会被调用close方法
    越晚声明的对象,会越早被close掉。
    try-with-resources处理机制详解
    JDK1.7开始,java引入了 try-with-resources 声明,将 try-catch-finally 简化为 try-catch,这其实是一种语法糖,在编译时会进行转化为 try-catch-finally 语句。新的声明包含三部分:try-with-resources 声明、try 块、catch 块。它要求在 try-with-resources 声明中定义的变量实现了 AutoCloseable 接口,这样在系统可以自动调用它们的close方法,从而替代了finally中关闭资源的功能。
    但是,它们的异常抛出机制发生了变化。在过去的 try-catch-finally 结构中,我们在finally块中关闭资源通常是这样的:

            catch (Exception e) {
           e.printStackTrace(); // 第一处异常处理
       }
       finally {
           try {
               if (c != null) {
                   c.close();
               }
           } catch (IOException e) {
               e.printStackTrace(); // 第二处异常处理
           }
       }


    异常处理有两种情况:

    try 块没有发生异常时,直接调用finally块,如果 close 发生异常,就处理。
    try 块发生异常,catch 块捕捉,进行第一处异常处理,然后调用 finally 块,如果 close 发生异常,就进行第二处异常处理。
    但是在 try-with-resources 结构中,异常处理也有两种情况(注意,不论 try 中是否有异常,都会首先自动执行 close 方法,然后才判断是否进入 catch 块,建议阅读后面的反编译代码):

    try 块没有发生异常时,自动调用 close 方法,如果发生异常,catch 块捕捉并处理异常。
    try 块发生异常,然后自动调用 close 方法,如果 close 也发生异常,catch 块只会捕捉 try 块抛出的异常,close 方法的异常会在catch 中被压制,但是你可以在catch块中,用 Throwable.getSuppressed 方法来获取到压制异常的数组。
    我们可以通过自定义的 AutoCloseable 类来理解这个过程。

    public class Main {
    
        public static void startTest() {
            try (MyAutoCloseA a = new MyAutoCloseA();
                 MyAutoCloseB b = new MyAutoCloseB()) {
                a.test();
                b.test();
            } catch (Exception e) {
                System.out.println("Main: exception");
                System.out.println(e.getMessage());
                Throwable[] suppressed = e.getSuppressed();
                for (int i = 0; i < suppressed.length; i++)
                    System.out.println(suppressed[i].getMessage());
            }
        }
    
        public static void main(String[] args) throws Exception {
            startTest();
        }
    }
    
    /* 输出为:
        MyAutoCloaseA: test()
        MyAutoCloseB: on close
        MyAutoCloseA: on close()
        Main: exception
        MyAutoCloaseA: test() IOException
        MyAutoCloaseB: close() ClassNotFoundException
        MyAutoCloaseA: close() ClassNotFoundException
    */
    
    class MyAutoCloseA implements AutoCloseable {
    
        public void test() throws IOException {
            System.out.println("MyAutoCloaseA: test()");
            throw new IOException("MyAutoCloaseA: test() IOException");
        }
    
        @Override
        public void close() throws Exception {
            System.out.println("MyAutoCloseA: on close()");
            throw new ClassNotFoundException("MyAutoCloaseA: close() ClassNotFoundException");
        }
    }
    
    class MyAutoCloseB implements AutoCloseable {
    
        public void test() throws IOException {
            System.out.println("MyAutoCloaseB: test()");
            throw new IOException("MyAutoCloaseB: test() IOException");
        }
        
        @Override
        public void close() throws Exception {
            System.out.println("MyAutoCloseB: on close");
            throw new ClassNotFoundException("MyAutoCloaseB: close() ClassNotFoundException");
        }
    }

    通过反编译class文件,可以看到实际的执行过程: 

        public static void startTest() {
           try {
               MyAutoCloseA a = new MyAutoCloseA();
               Throwable var33 = null;
    
               try {
                   MyAutoCloseB b = new MyAutoCloseB();
                   Throwable var3 = null;
    
                   try { // 我们定义的 try 块
                       a.test();
                       b.test();
                   } catch (Throwable var28) { // try 块中抛出的异常
                       var3 = var28;
                       throw var28;
                   } finally {
                       if (b != null) {
                           // 如果 try 块中抛出异常,就将 close 中的异常(如果有)附加为压制异常
                           if (var3 != null) {
                               try {
                                   b.close();
                               } catch (Throwable var27) {
                                   var3.addSuppressed(var27);
                               }
                           } else { // 如果 try 块没有抛出异常,就直接关闭,可能会抛出关闭异常
                               b.close();
                           }
                       }
    
                   }
               } catch (Throwable var30) {
                   var33 = var30;
                   throw var30;
               } finally {
                   if (a != null) {
                       if (var33 != null) {
                           try {
                               a.close();
                           } catch (Throwable var26) {
                               var33.addSuppressed(var26);
                           }
                       } else {
                           a.close();
                       }
                   }
    
               }
           // 所有的异常在这里交给 catch 块处理
           } catch (Exception var32) { // 我们定义的 catch 块
               System.out.println("Main: exception");
               System.out.println(var32.getMessage());
               Throwable[] suppressed = var32.getSuppressed();
    
               for(int i = 0; i < suppressed.length; ++i) {
                   System.out.println(suppressed[i].getMessage());
               }
           }
       }

    我还想补充的是:
    catch 块中,看不到 try-with-recourse 声明中的变量。
    try-with-recourse 中,try 块中抛出的异常,在 e.getMessage() 可以获得,而调用 close() 方法抛出的异常在e.getSuppressed() 获得。
    try-with-recourse 中定义多个变量时,由反编译可知,关闭的顺序是从后往前。

    JDK9中的改进
    作为 Milling Project Coin 的一部分, try-with-resources 中变量的声明在 JDK 9 已得到改进。如果你已经有一个资源是 final 或等效于 final 变量,您可以在 try-with-resources 语句中直接使用该变量,而无需在 try-with-resources 语句中声明一个新变量。

    JDK7、JDK8中的使用方式: 

    // A final resource
    final Resource resource1 = new Resource("resource1");
    // An effectively final resource
    Resource resource2 = new Resource("resource2");
    try (Resource r1 = resource1;
         Resource r2 = resource2) {
        // 使用resource1 and resource 2 通过变量r1 and r2.
    }

    JDK9中的使用方式: 

    // A final resource
    final Resource resource1 = new Resource("resource1");
    // An effectively final resource
    Resource resource2 = new Resource("resource2");
    try (resource1;
         resource2) {
        // 直接使用 resource1 and resource 2.
    }


     
    参考
    try-with-resources异常处理流程示例
    try-with-resource异常处理机制
    深入理解Java try-with-resource
    ————————————————
    版权声明:本文为CSDN博主「融极」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
    原文链接:https://blog.csdn.net/tianzhonghaoqing/article/details/118720380

  • 相关阅读:
    SystemParametersInfo调用失败的问题
    在wince下如何禁止移动窗体
    【转】WinCE控制面板添加应用程序
    CE6.0 下获得 SD 卡序列号的方法
    SetSystemMemoryDivision 的用法
    两经纬度之间的距离计算
    PC 上访问设备数据库的方法
    通过程序模拟鼠标按下
    车牌号
    比较字母大小
  • 原文地址:https://www.cnblogs.com/kelelipeng/p/16640431.html
Copyright © 2020-2023  润新知