try-with-resourcesJava 7부터 도입된 문법이며 사용한 자원을 해제하기 위해 사용한다.
try-with-resources 문법을 사용하기 위해서는 AutoCloseable 인터페이스를 구현해야 한다.
해당 인터페이스는 close() 메서드가 실행될 때까지 자원이 사용될 수 있도록 유지하며, try 블록이 종료될 때 자동으로 close() 메서드가 호출되도록 한다.
try-catch-finally(더 알아볼 것: 스택 트레이스 누락)
AutoClosableAutoClosable 인터페이스가 Closeable 인터페이스보다 늦게 추가된 것을 알 수 있다.JDBC - selectJDBC select 메서드를 예시로 사용하였다.
해당 메서드에서 사용하는 자원은 Connection, PreparedStatement, ResultSet이다.
먼저 try-catch-finally 구문을 사용한 코드이다.
밑단으로 갈수록 자원 해제와 관련된 코드가 길어져서 가독성이 떨어지는 것을 확인할 수 있다.
public static void selectAllMember() { String url = //url String id = //root String pwd = //pwd; String query = "SELECT * FROM member"; Connection connetion = null; PreparedStatement pstmt = null; ResultSet rs = null; try { connetion = DriverManager.getConnection(url, userName, password); pstmt.connection.prepareStatement(query); rs = pstmt.executeQuery() while (rs.next()) { int tableId = rs.getInt("id"); String name = rs.getString("name"); String job = rs.getString("job"); System.out.printf("id : %d name : %s job : %s", id, name, job); } } catch (SQLException e) { throw new RuntimeException(e); } finally { try { //자원 해제 rs.close(); pstmt.close(); connetion.close(); } catch (SQLExeption e) { throw new RuntimeException(e); } } }
try-with-resources 문법을 적용하여 구현한 select 메서드이다.
본래 try-with-resources 문법을 사용하기 위해서는 AutoCloseable 인터페이스 구현해야 하지만, Connection, PreparedStatement, ResultSet 모두 AutoCloseable 인터페이스를 구현하고 있으므로 생략한다.
자원 해제와 관련된 코드를 구현할 필요가 없어져 코드 가독성이 좋아지고, 코드가 간결해지는 것을 확인할 수 있다.
public abstract class MemberDB { private static final String url = //url private static final String id = //id private static final String pwd = //pwd /** * Member Select method */ public static void selectAllMember() { String query = new StringBuilder() .append("SELECT * ") .append("FROM member ").toString(); try (Connection connection = DriverManager.getConnection(url, id, pwd); PreparedStatement pstmt = connection.prepareStatement(query); ResultSet rs = pstmt.executeQuery()) { //try() 내부에 사용할 자원을 선언하면 된다. System.out.println("*".repeat(60)); while (rs.next()) { Member member = new Member( rs.getInt("id"), rs.getString("name"), rs.getString("job") ); System.out.println(member); } System.out.println("*".repeat(60)); } catch (SQLException e) { //예외 발생 시 Custom Exception 처리 throw new JdbcException(ErrorMessage.JDBC_SELECT_FAIL); } }