Java try-with-resources
정의
- try-with-resources 문에 하나 이상의 리소스(구분자 세미콜론(;)들을 선언
- java.io.Closeable을 구현하거나 java.lang.Autocloseable을 구현한 모든 객체를 리소스로 사용할 수 있다
- 기존의 try-catch-finally 구문에서는 리소스 누수의 위험이 있었다
- try-with-resources에서 catch블록, finally 블록은 리소스가 닫힌 후에 실행
Suppressed Exceptions
- try-with-resouces 문에서 여러 개의 예외가 발생할 시,
첫번째 예외는 정상적으로 처리되나 후속 예외는 억제된다(suppressed Exceptions)
- 첫번째 예외의 getSuppresedExceptions() 메서드를 호출하여 억제된 예외를 확인할 수 있다
public class SuppressedExceptionExample {
public static void main(String[] args) throws Exception {
try ( Door door = new Door() ) {
door.swing();
}
catch (Exception e) {
System.out.println("Primary Exception: " + e.getClass());
if (e.getSuppressed().length>0) {
System.out.print("Suppressed Exception: " + e.getSuppressed()[0]);
}
}
}
}