在除法函数中抛出MathCalculationException,但在控制台中显示ArithmeticException,我想显示ArithmeticException吗?
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))
预期:Exception $
MathCalculationException
实际的:ArithmeticException:/减零
最佳答案
我稍微注释了您的代码:
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
}
关于java - 如何解决MathCalculationException的异常问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57849976/