try with resource的错误用法

try with resource的错误用法

今天review一个老项目的代码,发现一些使用 try with resource 的错误使用,记录一下。

使用方法

try with resource 使用时,会按变量定义顺序,倒序关闭对象,但是,需注意,这里的多个对象,都需要明确的定义,如下:

代码示例

实际代码就不展示了,自己写了一个小例子来记录。

  1. 先定义两个类
public class Person implements AutoCloseable{
	public Person() {
		System.out.println("Person init");
	}
	
	@Override
	public void close() throws Exception {
		System.out.println("Person close");
	}
}

public class Child implements AutoCloseable{
	public Child() {
		System.out.println("Child init");
	}
	public Child(Person p) {
		System.out.println("Child init with Person");
	}
	
	@Override
	public void close() throws Exception {
		System.out.println("Child close");
	}
}


  1. 错误使用
public class Test {
	public static void main(String[] args) {
		try (Child c = new Child(new Person())) {
			System.out.println("try with resource");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

以上代码运行结果:
在这里插入图片描述
3. 正确使用

public class Test {
	public static void main(String[] args) {
		try (Person p = new Person();
				Child c = new Child(p)) {
			System.out.println("try with resource");
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}

以上代码运行结果:
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值