PHpullh
학습 라이브러리/Java/커스텀 예외 만들기

JAVA · 예외처리

커스텀 예외 만들기

도메인에 맞는 커스텀 예외를 올바르게 만드는 방법입니다.

예외처리중급커스텀예외예외설계도메인컨텍스트

핵심 설명

도메인에 맞는 커스텀 예외를 올바르게 만드는 방법입니다.

Java code

// 좋은 커스텀 예외
class InsufficientBalanceException extends RuntimeException {
    private final long currentBalance;
    private final long requestedAmount;

    InsufficientBalanceException(long current, long requested) {
        super(String.format("잔액 부족: 현재 %d, 요청 %d", current, requested));
        this.currentBalance = current;
        this.requestedAmount = requested;
    }

    long getCurrentBalance() { return currentBalance; }
    long getRequestedAmount() { return requestedAmount; }
    long getShortfall() { return requestedAmount - currentBalance; }
}

class Account {
    private long balance;

    Account(long balance) { this.balance = balance; }

    void withdraw(long amount) {
        if (amount > balance) {
            throw new InsufficientBalanceException(balance, amount);
        }
        balance -= amount;
    }
}

class Main {
    public static void main(String[] args) {
        Account acc = new Account(10000);
        try {
            acc.withdraw(15000);
        } catch (InsufficientBalanceException e) {
            System.out.println(e.getMessage());
            System.out.printf("부족액: %d원%n", e.getShortfall());
        }
    }
}

학습 팁

커스텀 예외에 진단에 필요한 컨텍스트 정보를 필드로 포함하세요. 로깅이나 에러 응답 생성에 유용합니다.

주의할 점

모든 예외를 Exception으로 던지면 호출자가 적절히 처리할 수 없습니다. 의미 있는 커스텀 예외를 정의하세요.

자주 묻는 질문

커스텀 예외 만들기란 무엇인가요?

도메인에 맞는 커스텀 예외를 올바르게 만드는 방법입니다.

커스텀 예외 만들기 학습 시 주의할 점은 무엇인가요?

모든 예외를 Exception 으로 던지면 호출자가 적절히 처리할 수 없습니다. 의미 있는 커스텀 예외를 정의하세요.