try with resource的错误用法
今天review一个老项目的代码,发现一些使用 try with resource 的错误使用,记录一下。
使用方法
try with resource 使用时,会按变量定义顺序,倒序关闭对象,但是,需注意,这里的多个对象,都需要明确的定义,如下:
代码示例
实际代码就不展示了,自己写了一个小例子来记录。
- 先定义两个类
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");
}
}
- 错误使用
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();
}
}
}
以上代码运行结果:

博客讨论了在Java中try-with-resources语句的错误使用情况,指出当在try块中初始化资源时,需要确保所有资源都实现了AutoCloseable接口。错误示例显示了未正确引用资源导致的问题,而正确示例则展示了如何按照顺序正确关闭资源。通过这种方式,可以避免资源泄露并确保程序的整洁和效率。


被折叠的 条评论
为什么被折叠?



