Reputation:
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
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
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
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