You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复MathCalculationException异常?除法函数需正确抛出目标异常

问题解答

嘿,我来帮你搞定这两个技术问题!

问题2:为什么抛出的是ArithmeticException而非MathCalculationException?

这是因为你的divide函数执行顺序出了问题:

  • 你先执行了val result = x/y,当y=0时,JVM会在计算除法的瞬间直接抛出内置的ArithmeticException: / by zero,此时你的if(y == 0) throw new MathCalculationException这段代码根本没机会运行。

修复方案(同时解决问题1和问题2)

要让自定义的MathCalculationException正常抛出,你需要先判断除数是否为0,再执行除法运算,同时还要注意Scala对Checked Exception的处理规则:

步骤1:调整divide函数的代码顺序

把除数检查放在最前面,确保在触发JVM内置异常之前抛出自定义异常:

def divide(x: Int, y: Int): Int = {
  if(y == 0) throw new MathCalculationException
  else x/y
}

步骤2:处理Checked Exception(可选但推荐)

因为你的MathCalculationException继承自Exception(属于Checked Exception),在Scala中调用这个函数时需要显式处理,否则编译器会报错。你有两个选择:

  • 选项A:把自定义异常改为继承RuntimeException(Unchecked Exception),这样调用时无需显式捕获:
    class MathCalculationException extends RuntimeException("Division by 0")
    
  • 选项B:在divide函数上声明抛出该异常,调用时用try-catch处理:
    import scala.util.control.Exception.catching
    
    def divide(x: Int, y: Int): Int = {
      if(y == 0) throw new MathCalculationException
      else x/y
    }
    
    // 调用时处理异常
    catching(classOf[MathCalculationException]) either PocketCalculator.divide(0,0) match {
      case Left(ex) => println(s"捕获到自定义异常:${ex.getMessage}")
      case Right(res) => println(s"计算结果:$res")
    }
    

验证修改后的效果

当你运行修改后的divide(0,0)时,控制台会输出:

Exception in thread "main" MathCalculationException: Division by 0
    at PocketCalculator$.divide(Main.scala:23)
    at Main$.main(Main.scala:30)
    at Main.main(Main.scala)

这就完全符合你的预期了!

内容的提问来源于stack exchange,提问作者arpana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:57:02