在此代码中实现了除法,因此我想处理3种使用try catch和throws未定义除法的情况,但它给我一个错误消息,即除法必须返回float。包计算器3;
// Class实现接口公共类实现实现calc {
//Add function
public int add(int x, int y) {
int ans1 = x + y ;
return ans1 ;
}
//Divide function
public float divide(int x, int y) throws RuntimeException{
try {
if(y == Double.POSITIVE_INFINITY || y == Double.NEGATIVE_INFINITY || y == 0 ) {
throw new ArithmeticException("invalid_division");
}
else {
return x / y ;
}
}catch (ArithmeticException invalid_division ) {
System.out.println("invalid_division");
}
}
}
您的divide
返回类型为float
。
int永远不会等于Double.POSITIVE_INFINITY
或Double.NEGATIVE_INFINITY
,因为它们不在可能的值范围内。
如果被捕获,该函数将不会引发错误。
获得3分以上:
//divide
public float divide(int x, int y) throws ArithmeticException{
if (y == 0) throw new ArithmeticException("invalid_division");
return (float)x / y; // cast x to float so a float will result
}
您在捕获到异常后实际上并未抛出异常,因此编译器将抱怨您在divide()
方法中缺少返回值。
添加:
throw e;
到您的catch子句