try-finally보다는 try-with-resources를 사용하라

  • try-with-resourcesAutoCloseable인터페이스를 구현해야한다.
  • 자바 라이브러리와 많은 서드파티 라이브러리들의 수 많은 클래스와 인터페이스가 이미 AutoCLoseable 을 구현한 상태다.
  • 닫아야 하는 자원을 쓰는 클래스를 만들어야한다면 AutoCloseable 을 반드시 구현하자.
  • try-with-resources 의 기본 형태
    try(InputStream in = new FileInputStream(src);
        OutputStream out = new FileOutputStream(dst)){
      ...
    }catch(IOException e) {
      ...
    }finally {
      ...
    }

+ Recent posts