java
runtime_error
ai_generated
true
java.lang.ArithmeticException: / by zero
ID: java/arithmeticexception-divide-by-zero
95%Fix Rate
90%Confidence
1Evidence
2023-05-12First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| Java 8 | active | — | — | — |
| Java 11 | active | — | — | — |
| Java 17 | active | — | — | — |
| Java 21 | active | — | — | — |
Root Cause
Integer division or modulo operation with a zero divisor, which is undefined in integer arithmetic.
generic中文
整数除法或取模运算的除数为零,这在整数算术中未定义。
Official Documentation
https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.htmlWorkarounds
-
95% success Check divisor before division: 'if (divisor == 0) { throw new IllegalArgumentException("Division by zero"); } else { result = dividend / divisor; }'
Check divisor before division: 'if (divisor == 0) { throw new IllegalArgumentException("Division by zero"); } else { result = dividend / divisor; }' -
85% success Use a safe division utility: 'public static int safeDivide(int a, int b) { if (b == 0) return 0; return a / b; }'
Use a safe division utility: 'public static int safeDivide(int a, int b) { if (b == 0) return 0; return a / b; }'
中文步骤
Check divisor before division: 'if (divisor == 0) { throw new IllegalArgumentException("Division by zero"); } else { result = dividend / divisor; }'Use a safe division utility: 'public static int safeDivide(int a, int b) { if (b == 0) return 0; return a / b; }'
Dead Ends
Common approaches that don't work:
-
75% fail
Using floating-point division (e.g., double) instead of integer division avoids the exception but may produce Infinity or NaN, which can propagate silently.
-
80% fail
Simply catching the exception and logging it without fixing the divisor can cause the application to produce incorrect results.