TIL

오늘의 오류. switch로 변수를 받을 때 NULL 값은 처리하지 못한다. (2024-07-26)

note994 2024. 7. 26. 14:08
public int calculate(int a, int b,char operator)throws Exception  {// throws Exception -> 이 메서드를 호출한 곳에서 오류를 처리해야 한다는 의미
    int res = 0;
    OperatorType type = OperatorType.getOperatorType(operator);
    switch (type) {
        case ADD:{
            AddOperator add = new AddOperator(a,b);
            res = add.operator();
            break;
        }
        case SUB:{
            SubtractOperator sub = new SubtractOperator(a,b);
            res = sub.operator();
            break;
        }
        case MUL:{
            MultiplyOperator mul = new MultiplyOperator(a,b);
            res =mul.operator();
            break;
        }
        case DIV:{
            if(b==0){
                throw new Exception("나눗셈 연산에서 분모(두번째 정수)에 0이 입력될 수 없습니다."); // 오류 메시지를 만들어서 호출한 곳으로 보낸다.
            }
            DivideOperator div = new DivideOperator(a,b);
            res =div.operator();
            break;
        }
        case MOD:{
            if(b==0){
                throw new Exception("나눗셈 연산에서 분모(두번째 정수)에 0이 입력될 수 없습니다."); // 오류 메시지를 만들어서 호출한 곳으로 보낸다.
            }
            ModOperator mod = new ModOperator(a,b);
            res = mod.operator();
            break;
        }
        default:{
            throw new Exception("사칙 연산 기호가 아닙니다 (+, -, *, /, %) 중 하나를 입력하세요");// 오류 메시지를 만들어서 호출한 곳으로 보낸다.
        }
    }

 

 

1. 4번째 줄 switch(type)의 type은 enum 상수이며 사칙연산 기호가 아닌값이 입력된 경우 NULL을 반환하도록 짜여져 있다.

 

2. 내 예상은 NULL값은 어느 case에도 없으므로 default가 실행될거라 예상했다.

 

3. 하지만 그냥 NullPointerException 오류가 발생할 뿐이다. 


해결법

OperatorType type;
type = OperatorType.getOperatorType(operator);
if(type == null){
    throw new Exception("사칙 연산 기호가 아닙니다 (+, -, *, /, %) 중 하나를 입력하세요");
}

1. type에 값을 할당하자마자 바로 검사해서 null일 경우 (입력기호가 잘못된 경우) 예외처리 실행