예외 상황에 대한 처리

3.1.1 예외처리 기능을 갖춘 DAO

정상적인 JDBC 코드의 흐름을 따르지 않고 중간에 어떤 이유로든 예외가 발생할 경우 사용한 리소스를 반드시 반환하도록 해야 한다.

JDBC 수정 기능의 예외처리 코드

public void deleteAll() throws SQLException{
  Connection c = dataSource.getConnection();

// 예외 발생 시 바로 메소드 **실행 중단**
  PreparedStatement ps = c.prepareStatement("delete from users");
  ps.executeUpdate();

  ps.close();
  c.close();
}

메소드에서 사용하는 자원: Connection, PreparedStatement

PreparedStatement 처리 중 예외 발생 시 바로 메소드를 나가게 된다.

ConnectionPreparedStatement 의 close() 메소드가 실행되지 않아서 리소스가 반환되지 않을 수 있다.

DB 커넥션 반환

서버에서 제한된 수의 DB 커넥션을 생성해 재사용 가능한 풀로 관리한다.

리소스 사용 시 유의사항

public void deleteAll() throws SQLException {
  Connection c = null;
  PreparedStatement ps = null;

  try {
    c = dataSource.getConnection();
    ps = c.prepareStatement("delete from users");
    ps.executeUpdate();
  } catch (SQLException e) {
    throw e;
  } finally {
    if (ps != null) {
      try {
        ps.close();
      } catch (SQLException e) {

      }
    }
    if (c != null){
      try{
        c.close();
      } catch (SQLException e){

      }
    }
  }
}