[책리뷰/Effective Java] 객체 생성과 파괴

OCTOBER 04, 2020

아이템9) try-finally 보다는 try-with-resources를 사용하라

꼭 회수해야 하는 자원을 다룰 때는 try-finally 말고 try-with-resources 를 사용하면 정확하고 쉽게 회수할 수 있다.

try-finally

  • try 안에서 예외가 발생한 후에 finally 안에서 또 다시 예외가 발생 한 경우에는,
    두번째 예외가 첫번째 예외를 집어삼키므로 디버깅이 어렵다.
void copy(String src, String dst) throws IOException {
  InputStream in = null;
  OutputStream out = null;
  try {
    in = new FileInputStream(src);
    out = new FileOutputStream(dst);

    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while((n = in.read(buf)) >= 0)
      out.write(buf, 0, n);

  } finally {
    if(in != null) in.close();
    if(out != null) out.close();
  }
}

try-with-resources

  • 코드가 간결해진다.
  • try 안에서 발생된 예외가 기록된다.
  • AutoCloseable 을 이용하여 닫아야하는 자원에 대해 정의할 수 있다.
    참고 - AutoCloseable 예제
void copy(String src, String dst) throws IOException {
  try (InputStream in = new FileInputStream(src); OutputStream out = new FileOutputStream(dst)) {
    byte[] buf = new byte[BUFFER_SIZE];
    int n;
    while((n = in.read(buf)) >= 0)
      out.write(buf, 0, n);
  }
}


작업 기록 블로그