我有一个具有开关块的功能我想在没有任何匹配时抛出异常我怎么能这样做我写了这个开关
private static int ClimateCal() {
int climateCal = 0;
switch (climate.toLowerCase()){
case "Hot":
climateCal = 0;
break;
case "Cold":
climateCal = 250;
break;
case "Moderate":
climateCal = 500;
break;
default:
Exception exception;
}
return climateCal;
}
答案 0 :(得分:4)
尝试
private static int ClimateCal() throws Exception { // Add throws keyword here If you want to catch the exception by the calling method.
int climateCal = 0;
switch (climate.toLowerCase()){
case "Hot":
climateCal = 0;
break;
case "Cold":
climateCal = 250;
break;
case "Moderate":
climateCal = 500;
break;
default:
throw new Exception();
}
return climateCal;
}
答案 1 :(得分:0)
就像你在任何时候抛出异常一样。
switch (condition){
case "A":
//do something
break;
case "B":
//do something
break;
default:
throw new Exception("oh no"); // or IllegalStateException or something
}
我只是在猜测,但你可能想要进一步了解链,所以更改方法的签名以传播异常:
private static int ClimateCal() throws Exception
如果存在一个约束条件,即气候只能是有限值集合中的一个,那么实际上您应该尝试在编译时而不是运行时强制执行此约束。我会声明一个枚举来表示可能的值:
enum Temperature
{
HOT (0),
COLD (250),
MODERATE (500);
private final int cal;
Temperature(final int cal)
{
this.cal = cal;
}
public int getCal()
{
return cal;
}
}
显然,你可以进一步充实。