JAVA - try~catch~resources 써보기

JDK 1.7 이상에서 try~catch~resources라는 기능이 있어서 써보기로 했다.
현재 사용 했던 방법은
try{
    PreparedStatement pstmt = null;
    ResultSet rs = null;
     
    ...
}
catch( Exception e ){
       ....
}
finally{
    if( pstmt != null ) try{pstmt.close();}catch(Exception e){}
    if( rs != null ) try{rs.close();}catch(Exception e){}
}

바꾼 후

try( PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery(); ){

}
catch( SQLException e){
e.printStackTrace()
}
요렇게 쓰면
finally에 따로 리소스를 안닫아 줘도 알아서 닫힌다고 한다.
단 위에서도 말했듯이 1.7이상에서만 써진다고 한다.

댓글