Java

try-with-resources ?

Terror123 2025. 2. 6. 15:58

개요

  • try-with-resources
  • try-finally의 차이점을 알 수 있습니다

try-with-resources

  • 자원을 자동으로 해제(close)해주는 Java의 예외 처리 구문입니다
  • close()를 직접 호출하지 않아도 자원을 안전하게 정리 할 수 있습니다

try-finally와의 차이

  • try-finally에서는 예외가 발생하여도 finally에서 close()를 호출해야했음
  • try-with-resources를 사용하면 finally없이 자동으로 close() 호출

기존 try-finally 방식

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;

try {
    conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
    pstmt = conn.prepareStatement("SELECT * FROM board");
    rs = pstmt.executeQuery();

    while (rs.next()) {
        System.out.println("게시글 제목: " + rs.getString("title"));
    }

} catch (SQLException e) {
    e.printStackTrace();
} finally {
    // 자원 해제 (수동으로 close() 호출)
    try {
        if (rs != null) rs.close();
        if (pstmt != null) pstmt.close();
        if (conn != null) conn.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

try-with-resources 방식

try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "user", "password");
     PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM board");
     ResultSet rs = pstmt.executeQuery()) { // ✅ `try()` 안에 선언한 자원은 자동으로 close() 호출됨

    while (rs.next()) {
        System.out.println("게시글 제목: " + rs.getString("title"));
    }

} catch (SQLException e) {
    e.printStackTrace();
}

결론

  • try-with-resources

    • 파일 읽기, DB연결, 네트워크 연결등에 적합
    • AutoCloseable을 구현한 객체를 사용할때만 적용 가능
  • try-catch-finally

    • 일반적인 예외처리, 비즈니스 로직에서 예외처리할때 사용

정리