JavaBookStudy / JavaBook

책읽기 스터디
https://javabookstudy.github.io/
Apache License 2.0
19 stars 2 forks source link

[토비의 스프링] 3.1 list 3-3 #76

Closed taxol1203 closed 3 years ago

taxol1203 commented 3 years ago

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 문은 리턴을 하기 전 반드시 방문을 하기 때문에, 리소스를 반납할 수 있는 것인가요?

daebalprime commented 3 years ago
public class FinallyTest {
    public static void main(String[] args) throws Exception{
        try {
//          int[] a = new int[4];
//          a[10000] = 200;
            System.out.println("try!");
            return;
        }catch(Exception e){

        }finally {
            System.out.println("finally!");
        }
    }
}

위 코드로 실험해보았습니다. Exception 일으켰을 시 출력:

try! finally!

Exception 발생하지 않을 시 출력:

finally!

return을 하던말던 finally는 무조건 실행 보장이 되는 듯 합니다.