try-with-resources
- try-with-resources는 try-catch-finally의 문제점(가독성, 실수 가능성, 자원누수)을 보완하기 위해 나온 개념
- try( ... ) 안에 자원 객체를 전달하면, try 블록이 끝나고 자동으로 자원 해제 해주는 기능
- 따로 finally 구문이나 모든 catch 구문에 종료 처리를 하지 않아도 되는 장점
- Java에서 외부 자원에 접근하는 경우 외부자원을 사용한 뒤 제대로 자원을 닫아줘야 한다. 자원을 닫을 때 try-catch-finally 보다 try-with-resources 구문을 사용하면 코드의 가독성이 더 증가한다.
try-catch-finally로 자원해제
FileOutputStream out = null;
try {
out = new FileOutputStream("exFile.txt");
}catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if(out != null) {
try {
out.close();
}catch (IOException e) {
e.printStackTrace();
}
}
}
try-with-resources로 자원 쉽게 해제
try(FileOutputStream out = new FileOutputStream("exFile.txt")) {
}catch (IOException e) {
e.printStackTrace();
}
- try(...)에 자원 객체를 전달하면, try 코드 블록이 끝나고 자동으로 자원을 해제한다. 즉, 따로 finally 구문이나 모든 catch 구문에 종료처리를 하지 않아도 된다.
- try-with-resources를 사용하기 위해서는(try에 전달할 수 있는 자원은) close() 를 정의하기 위한 AutoCloseable 인터페이스를 구현해야한다. cf) 복수의 자원객체도 가능하다.
- AutoCloseable 인터페이스를 구현한 대표적인 클래스(따로 구현X)
- FileInputStream / FileOutputStream: 파일 입출력에 사용됩니다.
- BufferedReader / BufferedWriter: 버퍼링된 문자 입력 및 출력에 사용됩니다.
- Scanner: 입력 스트림에서 텍스트를 읽는 데 사용됩니다.
- Socket / ServerSocket: 네트워크 통신에 사용됩니다.
- ZipInputStream / ZipOutputStream: ZIP 파일의 압축 해제 및 압축에 사용됩니다.
- ObjectInputStream / ObjectOutputStream: 객체의 직렬화 및 역직렬화에 사용됩니다.
AutoCloseable 인터페이스 구현 예제
- AutoCloseable 인터페이스를 구현하는 클래스에서는 close() 메서드만 오버라이딩하면 된다.(자원해제시 사용하는 메서드)
public class MyResource implements AutoCloseable {
@Override
public void close() throws Exception {
}
}
public class Main {
public static void main(String[] args) {
try (MyResource resource = new MyResource()) {
System.out.println("Inside try block");
} catch (Exception e) {
System.out.println("Exception caught: " + e);
}
}
}
참조 : https://dev-coco.tistory.com/20