Java 如何解决MathCalculationException的异常问题?
在除法函数中抛出了一个MathCalculationException,但在控制台中它显示了算术异常,我想显示算术异常Java 如何解决MathCalculationException的异常问题?,java,scala,Java,Scala,在除法函数中抛出了一个MathCalculationException,但在控制台中它显示了算术异常,我想显示算术异常 class OverFlowException extends RuntimeException class UnderFlowException extends RuntimeException class MathCalculationException extends Exception("Division by 0") object PocketCalcu
class OverFlowException extends RuntimeException
class UnderFlowException extends RuntimeException
class MathCalculationException extends Exception("Division by 0")
object PocketCalculator{
def add(x: Int, y: Int): Int = {
val result = x+y
if( x > 0 && y > 0 && result < 0 ) throw new OverFlowException
else if (x < 0 && y <0 && result > 0) throw new UnderFlowException
else result
}
def subtract(x: Int, y: Int):Int = {
val result = x - y
if(x > 0 && y <0 && result < 0 ) throw new OverFlowException
else if (x < 0 && y > 0 && result > 0) throw new UnderFlowException
else result
}
def multiply(x: Int, y: Int): Int = {
val result = x * y
if( x > 0 && y > 0 && result < 0) throw new OverFlowException
else if (x < 0 && y < 0 && result < 0) throw new OverFlowException
else if ( x < 0 && y > 0 && result > 0) throw new UnderFlowException
else if( x > 0 && y < 0 && result > 0) throw new UnderFlowException
else result
}
def divide(x: Int, y: Int): Int = {
val result = x/y
if(y == 0) throw new MathCalculationException
else result
}
}
// println(PocketCalculator.add(Int.MaxValue, 9))
println(PocketCalculator.divide(0, 0))
预期:异常$MathCalculationException
实际:算术异常:/by zero我已对您的代码稍加注释:
def divide(x: Int, y: Int): Int = {
val result = x/y // ArithmeticException raised here
if(y == 0) throw new MathCalculationException // never reached
else result
}
您可以改为:
def divide(x: Int, y: Int): Int = {
if(y == 0) throw new MathCalculationException
x/y
}
首先除以val result=x/y,然后检查y的值(如果y==0),使用lazy val或更改检查顺序(不需要结果)。在else处进行运算+、-、*,或/运算。