rspec/rules/S3518/java/rule.adoc
Fred Tingaud 6f24cc0632
Clean rule at root
In some cases, the `rule.adoc` at root of a rule is never included
anywhere and thus is dead code.
It's a maintenance cost by itself, but also it misses opportunities to
inline code that seems used by two documents when in fact only one
document is actually rendered. And this missed opportunity, in turn,
stops us from applying the correct language tag on the code samples.
2023-10-16 16:34:38 +02:00

96 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++``.
=== Message
Make sure 'xxxxx' can't be zero before doing this [division|modulation].
include::../highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]