java7 [try-with-resources]

try-with-resources

JDK7开始,支持try-with-resources.

    public class Savevarargs {

        public static void main(String[] args) throws Exception {

            try (OneCloseable one = new OneCloseable();
                 TwoCloseable two = new TwoCloseable()) {
                one.foo();
                two.foo();
            } catch (Exception e) {
                System.out.println("bom: " + e.getMessage());
                Arrays.stream(e.getSuppressed()).forEach(System.out::println);
            }
        }
    }

    class OneCloseable implements AutoCloseable {

        public OneCloseable() throws Exception {
            // throw new Exception("constructor exception....");
        }

        public void foo() throws Exception {
            throw new Exception("one method exception....");
        }

        @Override
        public void close() throws Exception {
            System.out.println("one closing.....");
            throw new Exception("one close excep...");
        }
    }

    class TwoCloseable implements AutoCloseable {

        public TwoCloseable() throws Exception {
            // throw new Exception("constructor exception....");
        }

        public void foo() throws Exception {
            throw new Exception("two method exception....");
        }

        @Override
        public void close() throws Exception {
            System.out.println("two closing.....");
            throw new Exception("two close excep...");
        }
    }
  1. try模块参数是resources,为final类型,不能在try-with-resources模块中再进行赋值
  2. try模块和try-with-resources模块执行如遇异常,将抛出,被catch或者向上抛出。这点和jdk7之前相同
  3. resource定义:实现了Closable或者Autoacloseable的对象
  4. try或者try-with-resources执行不管是否遇到异常,将调用resource.close()
  5. 多个resources用分号分隔,close()调用顺序与创建顺序相反
  6. 如果在当前resource.close()中遇到异常,并且此异常不是第一个,当前异常被抑制e.getSuppressed()获取被抑制的异常

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值