Java

[JAVA] 리소스 자동닫기와 예외 떠넘기기

개바리여리 2025. 10. 6. 21:08

리소스 사용을 위해 open을 하고 다 사용하고 안전하게 close를 해줘야 한다.

(파일을 읽었으면 안전하게 닫아야 한다.)

FileInputStream fis = null;
        try{
            fis = new FileInputStream("file.txt");
        }catch (Exception e){
            System.out.println("예외발생");
        }finally {
            fis.close();
        }
        
        
        //아래와 같이 변경가능
        
        try(FileInputStream fis = new FileInputStream("file.txt")){
            
        }catch(Exception e){
            
        }

 

아래에 try-with-resource 에 오는 객체는 AutoCloseable를 구현한 객체가 올 수 있다.

여러 객체를 사용할때는 세미콜론으로 구분해주면 된다.

 

 

 

예외 떠넘기기

메서드에서 직접 예외를 처리하지 않고, 호출한 쪽으로 예외를 떠넘기는 것.

 

import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ExceptionPropagationExample {

    //  예외를 발생시킬 가능성이 있는 메서드
    static void readFile() throws FileNotFoundException { 
        FileInputStream fis = new FileInputStream("test.txt"); // 없는 파일 가정
        System.out.println("파일을 읽습니다.");
    }

    // readFile()의 예외를 떠넘기는 메서드
    static void processFile() throws FileNotFoundException {
        System.out.println("파일 처리 시작");
        readFile(); // FileNotFoundException 발생 가능
        System.out.println("파일 처리 완료");
    }

    //  최종 호출자(main)에서 예외 처리
    public static void main(String[] args) {
        try {
            processFile();
        } catch (FileNotFoundException e) {
            System.out.println("예외 발생: 파일이 존재하지 않습니다.");
        }
        System.out.println("프로그램 정상 종료");
    }
}

 

보통 메서드 안에서 처리하기 애매할때 (해당 메서드에서 처리할 일이 아님)

이거나 공통 예외 처리 루틴이 따로 있을때 상위 메서드에서 한번만 처리하려는 목적으로 떠넘기기를 사용한다.