
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]
* 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]

=== Standards

* CWE - https://cwe.mitre.org/data/definitions/369[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
* STIG Viewer - https://stigviewer.com/stig/application_security_and_development/2023-06-08/finding/V-222612[Application Security and Development: V-222612] - The application must not be vulnerable to overflow attacks.


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[]
