BackendBench
Coffee

Home โ€บ Java exceptions โ€บ ArithmeticException

Unchecked exception ยท java.lang

ArithmeticException: causes and fixes

An integer division or modulo by zero, or an inexact BigDecimal result with no rounding mode.

What it looks like

java.lang.ArithmeticException: / by zero

Extends RuntimeException in java.lang.

What it means

Integer division and remainder by zero throw ArithmeticException, while floating point division by zero quietly returns Infinity or NaN. The second common source is BigDecimal: dividing without a scale or rounding mode throws "Non-terminating decimal expansion; no exact representable decimal result" when the quotient has infinitely many digits, as in 1 divided by 3. Math.addExact and friends also throw it on overflow.

Common causes

How to fix it

  1. Check the divisor before dividing, and decide what zero should mean (zero, null, an error).
  2. Pass a scale and rounding mode: a.divide(b, 2, RoundingMode.HALF_UP).
  3. Use the exact methods deliberately when silent overflow would be a bug.
  4. Validate configuration values such as page sizes and batch sizes at startup.

Broken and fixed

fails
int average = total / items.size(); // items empty -> / by zero
works
int average = items.isEmpty() ? 0 : total / items.size();

๐Ÿ”Ž Unravel the failing code ๐Ÿ”Ž Unravel the fix

In Spring and enterprise code

Money should be BigDecimal with an explicit rounding mode everywhere. A single divide without one is a runtime time bomb that only triggers for some values.

Debug it faster

Paste the whole stack trace into the stack trace beautifier to hide framework frames, jump to the root cause and find the first line of your own code. It runs in your browser, so the trace never leaves your machine.

Frequently asked questions

Is ArithmeticException a checked or unchecked exception?

ArithmeticException is an unchecked exception (it extends RuntimeException), so you are not forced to catch it. Prevent it with validation, or handle it where the input enters the system.

Which package is ArithmeticException in?

It lives in java.lang, so the import is import java.lang.ArithmeticException; (java.lang needs no import).

What is the first thing to check when I see ArithmeticException?

Read the message and the first stack trace line in your own code. The usual causes are: An int or long divisor that is zero: an empty list size, a missing count, a rate of zero; and BigDecimal.divide(other) with no MathContext or RoundingMode.

Related exceptions

More tools you might need