rspec/rules/S3518/java/rule.adoc

93 lines
2.4 KiB
Plaintext

If the denominator to an integer division or remainder operation is zero, a
`ArithmeticException` is thrown.
include::../introduction.adoc[]
== 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.
include::../impact.adoc[]
=== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
void test_divide() {
int z = 0;
if (unknown()) {
// ..
z = 3;
} else {
// ..
}
z = 1 / z; // Noncompliant, possible division by zero
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
void test_divide() {
int z = 0;
if (unknown()) {
// ..
z = 3;
} else {
// ..
z = 1;
}
z = 1 / z;
}
----
== Resources
=== Documentation
* https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/ArithmeticException.html[ArithmeticException]
=== Articles & blog posts
* https://cwe.mitre.org/data/definitions/369[MITRE, CWE-369] - Divide by zero
* https://wiki.sei.cmu.edu/confluence/x/CTZGBQ[CERT, NUM02-J.] - Ensure that division and remainder operations do not result in divide-by-zero errors
=== Standards
* https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.17.2[The Division Operator in the JLS]
* https://docs.oracle.com/javase/specs/jls/se17/html/jls-15.html#jls-15.17.3[The Remainder Operator in the JLS]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
This rule supports primitive ``++int++``, ``++long++``, ``++double++``, and
``++float++`` values, as well as ``++BigDecimal++`` and ``++BigInteger++``.
include::../message.adoc[]
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]