JAVA
try-with-resource
파란제이
2022. 7. 14. 01:28
close를 통해서 직접 닫아줘야되는 resource를 사용하는 경우 try-with-resource를 사용해서 자동으로 close를 시켜줄 수 있다. 자원들은 AutoCloseable interface를 구현해야한다.
아래와 같이 여러개의 자원을 사용하는 코드를 작성할 수 있다. 이 때는 자원을 생성한 순서의 역순으로 close를 해준다.
public class Main {
public static void main(String[] args) throws Exception {
try (TestResource testResource = new TestResource("1");
TestResource testResource2 = new TestResource("2")) {
System.out.println("in try");
throw new Exception();
} catch (Exception e) {
System.out.println("in catch");
} finally {
System.out.println("finally");
}
}
}
class TestResource implements AutoCloseable {
private String name;
public TestResource(String name) {
this.name = name;
}
@Override
public void close() throws Exception {
System.out.println(name + " close");
}
}
출력 결과
> Task :Main.main()
in try
2 close
1 close
in catch
finally
반응형