Language/Java

try - with - resources 문을 이용한 예외 처리

Seogineer 2020. 12. 21. 23:53
반응형

try - with - resources문

  • 자바7 버전에서 추가됨.
  • 입출력 처리시 예외가 발생하는 경우 JVM이 자동으로 close()를 호출하여 자원을 반납시켜준다.

try - catch문을 이용한 예외 처리

public List<Role> getRoles(){
    List<Role> list = new ArrayList<>();
    Connection conn = null;
    PreparedStatement ps = null;
    ResultSet rs = null;

    try {
        Class.forName("org.mariadb.jdbc.Driver");
        conn = DriverManager.getConnection(dburl, dbUser, dbPasswd);
        String sql = "SELECT description, role_id FROM role ORDER BY role_id DESC";
        ps = conn.prepareStatement(sql);
        rs = ps.executeQuery();
        while(rs.next()) {
            int id = rs.getInt("role_id");
            String description = rs.getString("description");
            Role role = new Role(id, description);
            list.add(role);
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    return list;
}

try - with - resources문을 이용한 예외 처리

public List<Role> getRoles(){
    List<Role> list = new ArrayList<>();

    try {
        Class.forName("org.mariadb.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }

    String sql = "SELECT description, role_id FROM role ORDER BY role_id DESC";

    try (
        Connection conn = DriverManager.getConnection(dburl, dbUser, dbPasswd);
        PreparedStatement ps = conn.prepareStatement(sql)
    ) {
        try (
            ResultSet rs = ps.executeQuery()
        ){
            while(rs.next()) {
                String description = rs.getString("description");
                int id = rs.getInt("role_id");
                Role role = new Role(id, description);
                list.add(role);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list;
}

참조

https://dololak.tistory.com/67

반응형