Java
Try With Resource
bambee83
2025. 1. 22. 15:53
try-with-resource는 Java 7에서 도입된 기능
리소스를 명시적으로 닫을 필요 없이 자동으로 닫아주는 기능을 제공
1. Try-with-Resource란?
java.lang.AutoCloseable 인터페이스를 구현한 리소스에 대해 사용할 수 있는 문법
try 블록이 끝나면 자동으로 해당 리소스의 close() 메서드를 호출
리소스를 명시적으로 닫지 않아도 되므로 코드가 간결하고 안전하며, 예외 처리를 보다 쉽게 관리가능
2. 기존 방식과의 비교
2-1. Java7 이전의 try-catch-finally
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("example.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2-2. Try-with-Resource 방식
try (ResourceType resource = new ResourceType()) {
// 리소스 사용
} catch (ExceptionType e) {
// 예외 처리
}
3. AutoCloseable과 Closeable의 차이
AutoCloseable:
Java 7에서 도입된 인터페이스, try-with-resource에서 사용
close() 메서드는 checked exception 또는 unchecked exception
Closeable:
Java 5에서 도입된 인터페이스, java.io 패키지의 클래스에서 주로 사용
close() 메서드는 반드시 IOException
AutoCloseable은 Closeable보다 더 일반화된 인터페이스,
예외 처리 방식에 유연성을 제공
5. 중첩 리소스 처리
try-with-resource를 사용하면 여러 리소스를 동시에 처리가능
try (
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))
) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
리소스를 여러 개 선언하면, 선언된 순서와 반대로 닫힌다
6. 장점
1. 리소스 누수 방지:
명시적으로 close()를 호출할 필요가 없으므로 실수로 리소스를 닫지 않는 문제를 방지
2. 가독성 향상:
코드가 간결하고 명확
3. 안전한 예외 처리:
리소스를 닫는 과정에서 발생하는 예외를 별도로 처리 X
4. 모든 에러에 대한 스택 트레이스 가능
7. 주의사항
1. try-with-resource는 선언된 리소스가 반드시 AutoCloseable을 구현
2. 리소스를 블록 외부에서 사용하려면 try-with-resource를 사용 불가
3. 예외가 발생하면 close() 메서드에서 던진 예외와 원래의 예외가 동시에 발생할 수 있으므로,
getSuppressed() 메서드로 추가 정보를 확인 필요
try (MyResource resource = new MyResource()) {
throw new RuntimeException("예외 발생");
} catch (Exception e) {
for (Throwable suppressed : e.getSuppressed()) {
System.out.println("Suppressed: " + suppressed);
}
}
참고 :