본문 바로가기

Language/Java

Try with Resources

1. 설명

AutoClosable이란 인터페이스를 구현한 클래스의 객체를 try구문 ()안에서 생성 했을 때를 가정한다. 

해당 객체가 try catch 구문을 다 지나갔으면, try 구문이 자동으로 close 매소드를 호출하여 close의 기능을 수행하게 한다.

 

해당 스킬은 클래스가 AutoClosable이라는 인터페이스를 구현 해야만 쓸 수 있다. 

2. 코드 리뷰 

import java.io.BufferedWriter;

public class _05_TryWithResources {
    public static void main(String[] args) {
    
    // close 구문도 예외처리가 필요해서 
    // try-catch-finally 구문 속에 또 try catch 구문이 들어간 걸 볼 수 있다.
    
       MyFileWriter writer1 = null;
       try {
           writer1 = new MyFileWriter();
           writer1.write("아이스크림이 먹고 싶어요.");
       }catch (Exception e){
           e.printStackTrace();
       } finally {
           try {
               writer1.close();
           } catch (Exception e) {
               throw new RuntimeException(e);
           }
       }
        // 위에 과정을 자동으로 하는 방법
        // try ()안에서 객체를 생성하면 try 구문이 자동으로 close 매소드를 호출해줌.
        // 이를 쓰기 위해서는 해당 객체의 클래스가 AutoClosable이란 interface를 구현해야함.
        
        //----- 자동으로 close 해주기에 무조건 실행하는 구문을 담는 finally가 필요 없다! 

        System.out.println("-------------------------");
       try (MyFileWriter writer2 = new MyFileWriter()) {
           writer2.write("빵이 먹고 싶어요.");
       } catch (Exception e) {
           e.printStackTrace();
       }

        BufferedWriter bw = null;

    }
}

class MyFileWriter implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("파일을 정상적으로 닫습니다.");
    }

    public void write(String line) {
        System.out.println("파일에 내용을 입력합니다.");
        System.out.println("입력 내용: " + line);
    }
}

3. 스스로 해보기 

public class TryWithResource_Myself {
    public static void main(String[] args) {
        FileWriter w1 = null;

        try {
            w1 = new FileWriter();
            w1.write("금수강산이 푸르구나.");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                w1.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

        System.out.println("----------------- 쉽게 하기 -------------------");

        try(FileWriter w2 = new FileWriter()) {

            w2.write("아아아 그리워라");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

class FileWriter implements AutoCloseable {

    @Override
    public void close() throws Exception {
        System.out.println("파일을 닫습니다.");
    }

    public void write(String line) {
        System.out.println("글을 적습니다. : " + line);
    }
}

'Language > Java' 카테고리의 다른 글

Throws (예외 처리 미루기)  (0) 2023.03.02
사용자 정의 예외  (0) 2023.03.02
Finally 구문  (0) 2023.02.28
Throw  (0) 2023.02.24
오류에 따른 맞춤 예외 처리  (0) 2023.02.23