美文网首页
【Java高级】必看!try-with-resource语法的一

【Java高级】必看!try-with-resource语法的一

作者: 大栗几 | 来源:发表于2020-06-08 17:56 被阅读0次

    本文为原创文章,转载请注明出处
    查看[Java]系列内容请点击:https://www.jianshu.com/nb/45938443

    当我们在通过try-with-resource语法进行资源关闭的时候,那么:

    try-with-resource会优先执行隐含的finally代码!!!

    即使你已经显式的写了finally,编译器还是会生成一个优先执行close()finally
    看下面示例:

    public class MainTest {
    
        public static void main(String[] args) {
            MyClass c = new MyClass();
            try (c) {
                System.out.println("in try clause.");
                throw new Exception();
            } catch (Exception e) {
                System.out.println("in catch clause.");
            } finally {
                System.out.println("in finally.");
            }
        }
    
    
        private static class MyClass implements Closeable {
    
            @Override
            public void close() {
                System.out.println("closed.");
            }
        }
    }
    

    输出结果:

    in try clause.
    closed.
    in catch clause.
    in finally.
    

    可以看到,系统首先执行了try代码块,然后在抛出异常的时候立即执行了close()操作,然后再执行catch代码块,最后执行我们自己定义的finally

    这点一定要注意,很容易出现暗坑!!!特别是你想在catch中在close()操作之前执行一些操作的时候,一定要注意!!!

    相关文章

      网友评论

          本文标题:【Java高级】必看!try-with-resource语法的一

          本文链接:https://www.haomeiwen.com/subject/vrtdtktx.html