본문 바로가기
Develops/JAVA

[JAVA] try-with-resources 활용하기 (자동 자원종료 기능)

by SLOTH91 2024. 11. 2.
반응형

최근엔 Java를 자주 개발하지 않지만 교육을 들으며, 알아두면 좋을 것 같은 문법을 발견하여 기록해둔다.

평소에 자원을 활용하는 코드를 작성할 때엔 무조건 try-catch-finally 문으로 마지막에 close() 를 해주는게 당연하다고 생각했는데, try-with-resources 구문을 활용하면 try문이 종료될 때 자동으로 자원을 종료해주니 코드도 간결해지고 가독성도 좋아질 것 같다는 생각이 들었다. 기억해두었다가 추후 개발을 하게 되면 활용해야겠다.

 

설명

try-with-resources이란?

  • try에 자원 객체를 전달하면, try 코드 블록이 끝나면 자동으로 자원을 종료해주는 기능
  • Java7부터 추가된 기능
  • AutoCloseable 인터페이스를 구현하고 있는 자원에 대해서만 지원

try-catch-finally로 close 처리를 해줬을 때의 단점

  • 자원 반납에 의해 코드가 복잡해짐
  • 작업이 번거로움
  • 실수로 자원을 반납하지 못하는 경우 발생
  • 에러로 자원을 반납하지 못하는 경우 발생
  • 에러 스택 트레이스가 누락되어 디버깅이 어려움

 

try-catch-finally 예시

public static void main(String args[]) throws IOException {
    FileInputStream is = null;
    BufferedInputStream bis = null;
    try {
        is = new FileInputStream("file.txt");
        bis = new BufferedInputStream(is);
        int data = -1;
        while((data = bis.read()) != -1){
            System.out.print((char) data);
        }
    } finally {
        // close resources
        if (is != null) is.close();
        if (bis != null) bis.close();
    }
}


try-with-resources 예시

public static void main(String args[]) throws IOException {
    try (FileInputStream is = new FileInputStream("file.txt");
         BufferedInputStream bis = new BufferedInputStream(is)) {
        int data;
        while ((data = bis.read()) != -1) {
            System.out.print((char) data);
        }
    }
}

 

 

[참고]

반응형