user2605953
user2605953

Reputation:

exception handling inside switch case

i want java exception where the case not + , - , * or / and on defualt i want to make exception show error like "Illegal arithmetic operation " on default

  private double evaluate(){
            double result ; 
           switch (operator) {
            case '-':
                result = left - right;
                break;
            case '*':
                result = left * right;
                break;
            case '/':
                result = left / right;
                break;
            case '+':
                result = left + right;
                break;
            default:   System.out.println ("ILLEGAL Arthemetic Operation " + operator);
             break;    //i want to show exception error here
        }
           return result;
           }

Upvotes: 0

Views: 4475

Answers (3)

Szymon
Szymon

Reputation: 43023

You can just throw an exception - you can do that in that place in the code in the same way as any other:

// ....
default:   
    System.out.println ("ILLEGAL Arthemetic Operation " + operator);
    throw new IllegalArgumentException("ILLEGAL Arthemetic Operation " + operator);
}

You don't need break; as it will never be reached.

Upvotes: 1

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can change your code as follows

 private double evaluate(char operator) throws Exception{
        double result ; 
       switch (operator) {
        case '-':
            result = left - right;
            break;
        case '*':
            result = left * right;
            break;
        case '/':
            result = left / right;
            break;
        case '+':
            result = left + right;
            break;
        default:  
            throw new Exception("Illegal Operation" + operator);
          }
       return result;
       }

Upvotes: 0

Prasad Kharkar
Prasad Kharkar

Reputation: 13556

You can simply throw the exception in default case

 default:   System.out.println ("ILLEGAL Arthemetic Operation " + operator);
            throw new Exception("Illegal Operation" + operator);

Upvotes: 1

Related Questions