213p. 리스트 3-3을 보시면, try catch를 사용하여 예외처리를 하였습니다.
기존 코드를 보시면,
public int getCount() throws SQLException {
Connection c = dataSource.getConnection();
PreparedStatement ps = c.prepareStatement("select count(*) from users");
ResultSet rs = ps.executeQuery();
rs.next();
int count = rs.getInt(1);
rs.close();
ps.close();
c.close();
return count;
}
와 같이 리소스를 close()로 반납한 뒤 return을 합니다.
하지만 예외 처리를 한 코드를 보면,
public int getCount() throws SQLException {
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
c = dataSource.getConnection();
ps = c.prepareStatement("select count(*) from users");
rs = ps.executeQuery();
rs.next();
return rs.getInt(1);
}catch (SQLException e) {
throw e;
}finally {
if(rs != null) {
try {
rs.close();
}catch (SQLException e) {
}
}
if(ps != null) {
try {
ps.close();
}catch (SQLException e) {
}
}
if(c != null) {
try {
c.close();
}catch (SQLException e) {
}
}
}
}
rs.next()를 수행 후 바로 리턴하는 것을 볼 수 있습니다.
혹시 try catch finally 문에서 finally 문은 리턴을 하기 전 반드시 방문을 하기 때문에, 리소스를 반납할 수 있는 것인가요?
213p. 리스트 3-3을 보시면, try catch를 사용하여 예외처리를 하였습니다.
기존 코드를 보시면,
와 같이 리소스를
close()로 반납한 뒤 return을 합니다.하지만 예외 처리를 한 코드를 보면,
rs.next()를 수행 후 바로 리턴하는 것을 볼 수 있습니다.혹시 try catch finally 문에서 finally 문은 리턴을 하기 전 반드시 방문을 하기 때문에, 리소스를 반납할 수 있는 것인가요?