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

Java中costToCompany为0时ArithmeticException未被捕获如何修复

问题根因

Java 中仅整数除以0会抛出ArithmeticException,浮点数除以0会得到Infinity(正无穷)、-Infinity(负无穷)或NaN(非数字),不会触发异常。
你的代码中被除数是两个double类型属性相减的结果,为浮点类型;除数强转int后会按照Java算术运算的类型提升规则自动转为double,最终运算是double / double,所以除0不会抛出预期异常。
另外你代码中对costToCompany的多余int强转还会导致计算精度丢失,比如成本为3.7时会被强转为3,利润率计算结果会出错。

修复方案

推荐使用前置校验替代异常捕获,逻辑更清晰也不会有精度问题,修复后代码如下:

public String calculateProfitMargin() {
      String returnMe = "";
      double profitMargin = 0;
      double costToCompany = orderItems[0].getItem().getCostToCompany();
      // 浮点类型避免精度误差,用绝对值判断是否接近0
      if (Math.abs(costToCompany) < 1e-6) {
         System.out.println("\nEXCEPTION CAUGHT\n________________");
         System.out.println("Details: / by Zero");
         System.out.println("To prevent this problem in the future DO NOT enter 0 as the cost to the company for any product in the system");
         System.exit(0);
      }
      profitMargin = (orderItems[0].getItem().getPriceSoldFor() - costToCompany) / costToCompany;
      returnMe = "The profit margin for Order " + orderNumber + " is: " + (profitMargin * 100) + "%";
      return returnMe;
}

如果一定要保留异常捕获的逻辑,需要把整个除法运算转为整数运算(不推荐,会损失精度),修改除法逻辑即可:

profitMargin = ( (int)(orderItems[0].getItem().getPriceSoldFor() - orderItems[0].getItem().getCostToCompany()) ) / ( (int) orderItems[0].getItem().getCostToCompany() );

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 18:18:01