Home โบ Java exceptions โบ ArithmeticException
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 zeroExtends 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
- An int or long divisor that is zero: an empty list size, a missing count, a rate of zero.
BigDecimal.divide(other)with noMathContextorRoundingMode.Math.toIntExact,addExactormultiplyExactdetecting overflow.- A modulo operation with a zero divisor, such as a page size of 0.
How to fix it
- Check the divisor before dividing, and decide what zero should mean (zero, null, an error).
- Pass a scale and rounding mode:
a.divide(b, 2, RoundingMode.HALF_UP). - Use the exact methods deliberately when silent overflow would be a bug.
- Validate configuration values such as page sizes and batch sizes at startup.
Broken and fixed
int average = total / items.size(); // items empty -> / by zeroint 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.