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.
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;
}
Exceptions
No issue is raised when the denominator is the constant zero, as it is considered an intentional failure.
When working with double
or float
values, no exception will be thrown, and the operation will result in special floating
point values representing either positive infinity, negative infinity, or NaN
. Thus, the rule does not apply to floating point division
or remainder operations.