[Java] try-with-resources

반응형

try-with-resources 는 try 에서 자원을 전달한 후 try 구문이 끝나고 나면 자원을 자동으로 종료해주는 기능 (auto close)이다

Java 7 이후부터 추가된 기능이며, 먼저 try-catch-finally 의 기능을 먼저 살펴보면 다음과 같다.

 

try-catch-finally

public static void main(String args[]) throws IOException {
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    try {
        fis = new FileInputStream("file.txt");
        bis = new BufferedInputStream(is);
        ...
    }catch(IOException e){
      ... 
   } finally {
        // close전 null인지 체크 
        if (is != null) is.close();
        if (bis != null) bis.close();
    }
}

    이 과정은 아래와 같은 단점을 가지고 있다

  • 실수로 자원해제를 못했을 경우 에러 발생
  • null인지 체크 후 각각 닫아줘야해서 코드가 복잡해짐

그래서 Java7 이후부터는 자원을 자동으로 close 해주는 try-with-resources 문법을 추가되었다.

 

try-with-resources

public static void main(String args[]) throws IOException {
   
    try(FileInputStream fis = new FileInputStream("file.txt")) {
      ...
    }catch(IOException e){
      ... 
   } 
}

 

 

다음과 같이 사용 시 코드의 간결함 뿐만 아니라 실수로 자원을 해체 시켜주지 않았을 시에 에러도 방지할 수 있고 

모든 에러에 대한 스택도 남길 수 있으므로 이와 같은 구문을 사용해야 할 경우 try-with-resources 를 쓰는게 더 유용하다

728x90
반응형

댓글