본문 바로가기
  • Adillete
【Java】

try-with-resources

by 아딜렛 2026. 3. 18.
try-with-resources
리소스를 자동으로 닫아주는 Java 문법
구조 비교
일반 try-catch-finally
BufferedReader br = ...;
try {
  br.readLine();
} catch (IOException e) {
  ...
} finally {
  br.close(); // 직접 닫아야 함
}
try-with-resources ✓
try (BufferedReader br = ...) {
  br.readLine();
} catch (IOException e) {
  ...
}
// br.close() 자동 호출됨
try (여기)  ← 이 괄호 안이 "with resource" 부분
블록 } 닫히는 순간 JVM이 close() 자동 호출 → catch/finally 도달 시 이미 닫힘
AutoCloseable — 도장
// AutoCloseable 인터페이스 (내부는 이게 전부)
public interface AutoCloseable {
    void close() throws Exception;
}

// try 괄호에 넣으려면 implements 필수
class MyResource implements AutoCloseable {
    @Override
    public void close() {
        System.out.println("닫힘");
    }
}

// 사용
try (MyResource r = new MyResource()) {
    System.out.println("작업 중");
}
// 출력: 작업 중 → 닫힘
✓ OK
try (BufferedReader br
     = new BufferedReader(...))
// BufferedReader → AutoCloseable 구현됨
✗ 컴파일 에러
class Foo {}
try (Foo f = new Foo())
// Foo → AutoCloseable 없음
핵심 요약
1. try (선언) 괄호 = "with resource" 부분
2. 블록 끝나면 close() 자동 호출 — finally 불필요
3. 괄호 안에 넣으려면 implements AutoCloseable 도장 필수
4. 상속(extends) ❌  →  구현(implements) ✓  — AutoCloseable은 인터페이스