ArithmeticException
JavaERRORCommonMath

Arithmetic error — usually division by zero

Quick Answer

Guard against zero divisors before dividing; for BigDecimal always specify a RoundingMode.

What this means

Thrown when an exceptional arithmetic condition occurs. The most common cause is integer division or modulo by zero.

Why it happens
  1. 1Dividing an int or long by zero
  2. 2BigDecimal.divide() with non-terminating decimal and no rounding mode

Fix

Guard divisor and use RoundingMode for BigDecimal

Guard divisor and use RoundingMode for BigDecimal
int result = (divisor != 0) ? (a / divisor) : 0;
BigDecimal r = a.divide(b, 10, RoundingMode.HALF_UP);

Why this works

Checking the divisor prevents the exception; RoundingMode makes BigDecimal division always terminate.

Code examples
Triggerjava
int x = 10 / 0; // ArithmeticException: / by zero
Safe dividejava
static int safeDivide(int a, int b) {
    return b == 0 ? 0 : a / b;
}
BigDecimal with roundingjava
BigDecimal result = new BigDecimal("1")
    .divide(new BigDecimal("3"), 10, RoundingMode.HALF_UP);
Sources
Official documentation ↗

Java SE Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Java errors