Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท java.lang

The ArithmeticException class

Reference for java.lang.ArithmeticException: integer division and remainder by zero, the Math exact methods, BigDecimal rounding errors and how to avoid them.

java.lang.ArithmeticException is an unchecked exception that signals an exceptional arithmetic condition. The classic case is integer division or remainder by zero: 5 / 0 throws ArithmeticException with the message / by zero.

Floating-point arithmetic does not throw: 5.0 / 0 is Infinity, 0.0 / 0 is NaN. The exception also comes from the "exact" arithmetic methods of Math (overflow), from BigInteger and BigDecimal (division by zero, non-terminating decimals), and from a few other APIs such as Duration.

Java
public class ArithmeticException extends RuntimeException

Try it

Java Integer versus floating-point division

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java BigDecimal and checks before dividing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public ArithmeticException()
public ArithmeticException(String s)
Constructor Description
ArithmeticException() No detail message.
ArithmeticException(String s) Detail message returned by getMessage().

Usage notes

  • Only integer types throw on / and % by zero (byte, short, int, long, char). double and float follow IEEE 754 and produce Infinity or NaN.
  • Overflow is silent by default. Integer.MAX_VALUE + 1 wraps to a negative number. Use Math.addExact, subtractExact, multiplyExact, incrementExact, toIntExact and friends when overflow must be an error; they throw ArithmeticException with the message integer overflow or long overflow.
  • BigDecimal.divide(BigDecimal) throws when the exact quotient has a non-terminating decimal expansion (Non-terminating decimal expansion; no exact representable decimal result.). Pass a scale and a RoundingMode, or a MathContext.
  • BigInteger throws BigInteger divide by zero for division by zero and BigInteger: modulus not positive for mod with a non-positive modulus.
  • Prevent rather than catch. Check the divisor before dividing when zero is a possible, ordinary input. Catching the exception is appropriate at a boundary, such as a calculator that reports "cannot divide by zero".
  • Integer.MIN_VALUE / -1 does not throw; it overflows and returns Integer.MIN_VALUE. Math.divideExact reports it.
  • Floating-point checks: use Double.isNaN(), Double.isInfinite() or Double.isFinite() to detect the non-throwing cases.