Java Exception에 변수 추가하기

2024. 11. 30. 07:33Java

class SpecialValueException extends Exception {
    private final int specialValue;

    public SpecialValueException(String message, int specialValue) {
        super(message);
        this.specialValue = specialValue;
    }

    public int getSpecialValue() {
        return specialValue;
    }
}

public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            processNumber(-5);
        } catch (SpecialValueException e) {
            System.err.println("Error: " + e.getMessage());
            System.out.println("Special Value: " + e.getSpecialValue());
        }
    }

    public static void processNumber(int number) throws SpecialValueException {
        if (number < 0) {
            throw new SpecialValueException("Negative number detected", 42);
        }
    }
}