Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何解决MathCalculationException的异常问题?_Java_Scala - Fatal编程技术网

Java 如何解决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

在除法函数中抛出了一个MathCalculationException,但在控制台中它显示了算术异常,我想显示算术异常

 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处进行运算+、-、*,或/运算。