If the denominator to an integer division or remainder operation is zero, a ArithmeticException
is thrown.
This error will crash your program in most cases. To fix it, you need to ensure that the denominator value in all division operations is always
non-zero, or check the value against zero before performing the division.
Why is this an issue?
A division (/
) or remainder operation (%
) by zero indicates a bug or logical error. This is because in Java, a division
or remainder operation where the denominator is zero and not a floating point value always results in an ArithmeticException
being
thrown.
When working with double
or float
values, no exception will be thrown, but the operation will result in special floating
point values representing either positive infinity, negative infinity, or NaN
. Unless these special values are explicitly handled by a
program, zero denominators should be avoided in floating point operations, too. Otherwise, the application might produce unexpected results.
What is the potential impact?
Issues of this type interrupt the normal execution of a program, causing it to crash or putting it into an inconsistent state. Therefore, this
issue might impact the availability and reliability of your application, or even result in data loss.
If the computation of the denominator is tied to user input data, this issue can potentially even be exploited by attackers to disrupt your
application.
Noncompliant code example
void test_divide() {
int z = 0;
if (unknown()) {
// ..
z = 3;
} else {
// ..
}
z = 1 / z; // Noncompliant, possible division by zero
}
Compliant solution
void test_divide() {
int z = 0;
if (unknown()) {
// ..
z = 3;
} else {
// ..
z = 1;
}
z = 1 / z;
}
Resources
Documentation
Articles & blog posts
Standards