PHpullh
학습 라이브러리/Java/예외 처리 & try-with-resources

JAVA · 예외처리

예외 처리 & try-with-resources

Checked/Unchecked 예외, 커스텀 예외 계층, try-with-resources로 리소스를 안전하게 관리합니다.

예외처리입문try-with-resourcesAutoCloseablemulti-catchCheckedUnchecked

핵심 설명

Checked/Unchecked 예외, 커스텀 예외 계층, try-with-resources로 리소스를 안전하게 관리합니다.

Java code

import java.io.*;

// 커스텀 예외 계층
public class AppException extends RuntimeException {  // Unchecked
    private final int errorCode;

    public AppException(String message, int errorCode) {
        super(message);
        this.errorCode = errorCode;
    }

    public AppException(String message, int errorCode, Throwable cause) {
        super(message, cause);
        this.errorCode = errorCode;
    }

    public int getErrorCode() { return errorCode; }
}

public class NotFoundException extends AppException {
    public NotFoundException(String resource, long id) {
        super("%s #%d를 찾을 수 없습니다".formatted(resource, id), 404);
    }
}

public class ExceptionDemo {
    // try-with-resources — AutoCloseable 자동 닫기
    static String readFile(String path) throws IOException {
        try (var reader = new BufferedReader(new FileReader(path))) {
            var sb = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                sb.append(line).append(System.lineSeparator());
            }
            return sb.toString();
        }
    }

    // 멀티 catch (Java 7+)
    static void process(String input) {
        try {
            int n = Integer.parseInt(input);
            int[] arr = new int[n];
            arr[n] = 1;  // 일부러 에러
        } catch (NumberFormatException | NegativeArraySizeException e) {
            System.out.println("입력 오류: " + e.getMessage());
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("범위 초과: " + e.getMessage());
        } finally {
            System.out.println("항상 실행");
        }
    }

    public static void main(String[] args) {
        // 예외 체이닝
        try {
            throw new AppException("DB 연결 실패", 500,
                new RuntimeException("Connection timeout"));
        } catch (AppException e) {
            System.out.println(e.getMessage() + " [" + e.getErrorCode() + "]");
            System.out.println("원인: " + e.getCause().getMessage());
        }
        process("3");
    }
}

학습 팁

RuntimeException(Unchecked)을 상속하면 throws 선언 없이 사용 가능합니다. 현대 Java에서는 Checked Exception보다 Unchecked Exception이 선호됩니다.

주의할 점

catch (Exception e) {}처럼 빈 catch 블록은 절대 작성하지 마세요. 최소한 로그라도 남겨야 합니다.

자주 묻는 질문

예외 처리 & try-with-resources란 무엇인가요?

Checked/Unchecked 예외, 커스텀 예외 계층, try-with-resources로 리소스를 안전하게 관리합니다.

예외 처리 & try-with-resources 학습 시 주의할 점은 무엇인가요?

catch (Exception e) {} 처럼 빈 catch 블록은 절대 작성하지 마세요. 최소한 로그라도 남겨야 합니다.