如何解决MathCalculationException的异常问题?

时间:2019-09-09 08:03:13

标签: java scala

在除法函数中抛出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))

预期:例外$ MathCalculationException 实际的:ArithmeticException:/减零

1 个答案:

答案 0 :(得分:1)

我为您的代码做了一些注释:

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
}