본문 바로가기

Java 기본 문법 - 참조 서적 [이것이 자바다 - 한빛미디어]/8. 예외 처리

3. Java 자바 [예외 처리] - 자동 리소스 닫기 try - with - resource 문

 

 

자바 7 버전 부터 새로 추가 된 try - with - resource 를 사용하면 예외 발생 여부와 상관 없이 사용했던

리소스 객체 ( 각종 입출력 스트림, 서버 소켓, 소켓, 각종 채널 등..) 의 close() 메소드를 호출하여

안전하게 리소스를 닫아준다.

 

리소스 : 데이터를 읽고 쓰는 객체

 

ex) 파일의 데이터를 읽는 FileInputStream 객체, 파일에 쓰는 FileOutputStream 리소스 객체

 

자바 6 이전 버전의 코드

 

FileInputStream fis = null;

 

try {

    fis = new FileInputStream("file.txt");

    . . . 

} catch(IOException e) {

    . . . 

} finally {

    if(fis != null) {

        try {

            fis.close();

        } catch (IOException e) {   }

    }

}

 

 

try - with - resource 문 사용 ( close() 메소드를 명시할 필요가 없다.)

 

try 의 ( ) 부분에 resource 객체 구문이 들어간다.

 

try(FileInputStream fis = new FileInputStream("file.txt")) {

    . . .

} catch(IOException e) {

    . . . 

}

 

try 블록이 정상적으로 실행을 완료했거나, 도중에 예외가 발생하면,

자동으로 FileOutputStream 의 close() 메소드가 호출된다.

 

try 블록에서 예외가 발생하면, 우선 close() 로 리소스를 닫고, catch 블록을 실행한다.

 

 

복수 개의 리소스를 사용 할 때

 

try (

    FileInputStream fis = new FileInputStream(“file1.txt”);

    FileOutputSteam fos = new FileOutputSteam(“file2.txt”);

    ) {

    ...

} catch(IOException e) {

    ...

}

 

 

try - with - resource 사용 조건

 

리소스 객체는 java.lang.AutoCloseable 인터페이스를 구현하고 있어야 한다.

 

AutoCloseable에는 close() 메소드가 정의되어 있고 try – with – resource는 이 close() 메소드를 자동 호출한다.

 

(API 도큐먼트에서 AutoCloseable 인터페이스에서“All Known Implementing Classes:” 에서

try-with-resource 와 함께 사용할 수 있는 리소스가 어떤 것이 있는 지 알 수 있다.)

 

ex) FileInputStream.java : AutoCloseable 구현 클래스

 

public class FileInputStream implements AutoCloseable {
    private String file;
    
    public FileInputStream(String file) {
        this.file = file;
    }
    
    public void read() {
        System.out.println(file + "을 읽습니다.");
    }
    
    @Override
    public void close() throws Exception {
        System.out.println(file + "을 닫습니다.");
    }
}

 

ex) TryWithResourceExam.java : AutoCloseable

 

public class TryWithResourceExam {
    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("file.txt")) {
            fis.read();              // file.txt 을 읽습니다.
            throw new Exception();   // 강제로 예외를 발생시킴!! file.txt 을 닫습니다. 먼저 출력된다.
        } catch(Exception e) {
            System.out.println("예외 처리 코드 실행!");   // 마지막에 출력됨
        }
    }
}

 

예외가 발생하면 자동으로 FileInputStream 의 close() 메소드가 자동으로 호출되어

"file.txt" 을 닫습니다 가 출력된다.