PHpullh
학습 라이브러리/Java/예외 체이닝

JAVA · 예외처리

예외 체이닝

예외의 원인 체인을 활용하여 근본 원인을 추적합니다.

예외처리중급예외체이닝causegetRootCause디버깅

핵심 설명

예외의 원인 체인을 활용하여 근본 원인을 추적합니다.

Java code

public class ExceptionChaining {
    // 근본 원인 추출 유틸리티
    static Throwable getRootCause(Throwable t) {
        Throwable root = t;
        while (root.getCause() != null && root.getCause() != root) {
            root = root.getCause();
        }
        return root;
    }

    // 예외 체인 출력
    static void printChain(Throwable t) {
        Throwable current = t;
        int depth = 0;
        while (current != null) {
            System.out.printf("%s[%d] %s: %s%n",
                "  ".repeat(depth),
                depth,
                current.getClass().getSimpleName(),
                current.getMessage());
            current = current.getCause();
            depth++;
        }
    }

    public static void main(String[] args) {
        try {
            try {
                try {
                    throw new java.io.IOException("디스크 가득 참");
                } catch (java.io.IOException e) {
                    throw new RuntimeException("파일 저장 실패", e);
                }
            } catch (RuntimeException e) {
                throw new IllegalStateException("주문 처리 실패", e);
            }
        } catch (IllegalStateException e) {
            System.out.println("=== 예외 체인 ===");
            printChain(e);
            System.out.println("\n근본 원인: " +
                getRootCause(e).getMessage());
        }
    }
}

학습 팁

Throwable.getCause()로 원인 체인을 탐색합니다. 프레임워크에서는 ExceptionUtils.getRootCause()(Apache Commons)를 활용하세요.

주의할 점

예외 체인에서 순환 참조가 발생하면 무한 루프입니다. getCause() != this 검사를 추가하세요.

자주 묻는 질문

예외 체이닝란 무엇인가요?

예외의 원인 체인을 활용하여 근본 원인을 추적합니다.

예외 체이닝 학습 시 주의할 점은 무엇인가요?

예외 체인에서 순환 참조가 발생하면 무한 루프입니다. getCause() != this 검사를 추가하세요.