PHpullh
학습 라이브러리/Java/multi-catch와 예외 재던지기

JAVA · 예외처리

multi-catch와 예외 재던지기

여러 예외를 한 번에 잡는 multi-catch와 예외 재던지기 패턴입니다.

예외처리중급multi-catch예외래핑cause재던지기

핵심 설명

여러 예외를 한 번에 잡는 multi-catch와 예외 재던지기 패턴입니다.

Java code

import java.io.*;
import java.sql.*;

public class MultiCatch {
    // multi-catch (Java 7+)
    static void handleMultiple(String input) {
        try {
            if (input.equals("io")) throw new IOException("I/O 에러");
            if (input.equals("num")) throw new NumberFormatException("숫자 에러");
            if (input.equals("sql")) throw new SQLException("DB 에러");
        } catch (IOException | NumberFormatException e) {
            // 여러 예외를 하나의 catch로
            System.out.println("처리: " + e.getClass().getSimpleName());
            // e는 암묵적 final — 재할당 불가
        } catch (SQLException e) {
            System.out.println("DB: " + e.getMessage());
        }
    }

    // 예외 래핑 후 재던지기
    static void process() {
        try {
            riskyOperation();
        } catch (IOException e) {
            // 원인 체인 유지하면서 래핑
            throw new RuntimeException("처리 실패", e);
        }
    }

    static void riskyOperation() throws IOException {
        throw new IOException("원본 에러");
    }

    public static void main(String[] args) {
        handleMultiple("io");
        handleMultiple("num");

        try {
            process();
        } catch (RuntimeException e) {
            System.out.println("예외: " + e.getMessage());
            System.out.println("원인: " + e.getCause().getMessage());
        }
    }
}

학습 팁

multi-catch에서 상위-하위 예외를 함께 쓸 수 없습니다. IOException | Exception은 컴파일 에러입니다.

주의할 점

예외를 래핑할 때 원인(cause)을 전달하지 않으면 디버깅 시 원본 스택 트레이스를 잃습니다. 항상 new RuntimeException(msg, cause)를 사용하세요.

자주 묻는 질문

multi-catch와 예외 재던지기란 무엇인가요?

여러 예외를 한 번에 잡는 multi-catch와 예외 재던지기 패턴입니다.

multi-catch와 예외 재던지기 학습 시 주의할 점은 무엇인가요?

예외를 래핑할 때 원인( cause )을 전달하지 않으면 디버깅 시 원본 스택 트레이스를 잃습니다. 항상 new RuntimeException(msg, cause) 를 사용하세요.