java runtime_error ai_generated true

java.lang.ArithmeticException: 除以零

java.lang.ArithmeticException: / by zero

ID: java/arithmeticexception-divide-by-zero

其他格式: JSON · Markdown 中文 · English
95%修复率
90%置信度
1证据数
2023-05-12首次发现

版本兼容性

版本状态引入弃用备注
Java 8 active
Java 11 active
Java 17 active
Java 21 active

根因分析

整数除法或取模运算的除数为零,这在整数算术中未定义。

English

Integer division or modulo operation with a zero divisor, which is undefined in integer arithmetic.

generic

官方文档

https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html

解决方案

  1. Check divisor before division: 'if (divisor == 0) { throw new IllegalArgumentException("Division by zero"); } else { result = dividend / divisor; }'
  2. Use a safe division utility: 'public static int safeDivide(int a, int b) { if (b == 0) return 0; return a / b; }'

无效尝试

常见但无效的做法:

  1. 75% 失败

    Using floating-point division (e.g., double) instead of integer division avoids the exception but may produce Infinity or NaN, which can propagate silently.

  2. 80% 失败

    Simply catching the exception and logging it without fixing the divisor can cause the application to produce incorrect results.