--- id: java-try-catch-resources title: "Java Try Catch Resources" category: "Programming_Language" status: "draft" verification_status: "conceptual" canonical_id: "" aliases: ["try-with-resources", "자바 리소스 자동 종료"] duplicate_of: "" source_trust_level: "B" confidence_score: 0.88 created_at: 2026-07-04 updated_at: 2026-07-04 review_reason: "" merge_history: [] tags: ["java", "programming", "w3schools", "exceptions", "try-with-resources", "io"] raw_sources: ["https://www.w3schools.com/java/java_try_catch_resources.asp"] applied_in: [] github_commit: "" --- # [[Java Try Catch Resources]] ## 🎯 한 줄 통찰 (One-line insight) try-with-resources closes the declared resource automatically EVEN IF an exception occurs mid-block — this is strictly safer than manual `.close()` calls, since a manual close placed after the risky code (like `output.write()`) never executes if that code throws first. [S1] ## 🧠 핵심 개념 (Core concepts) - **Manual resource closing (old style)** — must call `.close()` explicitly; if an exception occurs before that call, the resource leaks. [S1] - **`try-with-resources`** (Java 7+) — the resource is declared inside `try(...)`; Java closes it automatically when the block ends, even on error. [S1] - **Applies to** — files, streams, database connections — anything with a `close()` method. [S1] - **Benefits** — safer (guaranteed close), cleaner (no explicit close() calls), shorter (less boilerplate). [S1] ## 📖 세부 내용 (Details) - Manual close (risk: skipped if write() throws before reaching close()): `FileOutputStream output = new FileOutputStream("filename.txt"); output.write("Hello".getBytes()); output.close(); // must close manually`. [S1] - Try-with-resources (guaranteed close): `try (FileOutputStream output = new FileOutputStream("filename.txt")) { output.write("Hello".getBytes()); // no need to call close() here } catch (IOException e) { System.out.println("Error writing file."); }`. [S1] ## ⚖️ 모순 및 업데이트 (Contradictions & updates) - **수동 close()의 위험**: 예외 발생 전에 write()가 실패하면 close() 호출부에 도달하지 못해 리소스가 열린 채로 남는다는 점이 명시적으로 지적됨. [S1] ## 🛠️ 적용 사례 (Applied in summary) 현재 발견된 실제 적용 사례가 없습니다 — 파일/스트림/DB 연결 작업 시 반드시 try-with-resources를 사용하라는 실전 규칙(rule of thumb)이 제시됨. [S1] ## 💻 코드 패턴 (Code patterns) Try-with-resources guarantees automatic close (Java): ```java import java.io.FileOutputStream; import java.io.IOException; try (FileOutputStream output = new FileOutputStream("filename.txt")) { output.write("Hello".getBytes()); // no need to call close() here } catch (IOException e) { System.out.println("Error writing file."); } ``` ## ✅ 검증 상태 및 신뢰도 - **상태:** draft - **검증 단계:** conceptual - **출처 신뢰도:** B (W3Schools — widely used educational reference, not a primary standards body) - **신뢰 점수:** 0.88 - **중복 검사 결과:** 신규 생성 (New discovery) ## 🔗 지식 그래프 (Knowledge Graph) - **상위/루트:** [[Java Tutorial]] - **관련 개념:** [[Java Exceptions Multiple]], [[Java Files]], [[Java IO Streams]] - **참조 맥락:** 자원 자동 해제 — Files & I/O 섹션의 직접적 도입부. ## 📚 출처 (Sources) - [S1] W3Schools — Java try-with-resources — https://www.w3schools.com/java/java_try_catch_resources.asp ## 📝 변경 이력 (Change history) - 2026-07-04: Initial draft synthesized from the W3Schools "Java Close Resources" page (Astra wiki-curation, P-Reinforce v3.1 format).