我想要java异常,其中大小写不是+, - ,*或/并且默认情况下我想让异常显示错误,如默认情况下的“非法算术运算”
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;
}
答案 0 :(得分:1)
您可以简单地在default
案例
default: System.out.println ("ILLEGAL Arthemetic Operation " + operator);
throw new Exception("Illegal Operation" + operator);
答案 1 :(得分:1)
你可以抛出异常 - 你可以在代码中的那个位置以与其他任何方式相同的方式执行此操作:
// ....
default:
System.out.println ("ILLEGAL Arthemetic Operation " + operator);
throw new IllegalArgumentException("ILLEGAL Arthemetic Operation " + operator);
}
您不需要break;
,因为它永远无法到达。
答案 2 :(得分:0)
您可以按照以下方式更改代码
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;
}