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.
public class ArithmeticException extends RuntimeException
Try it
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.
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
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).doubleandfloatfollow IEEE 754 and produceInfinityorNaN. - Overflow is silent by default.
Integer.MAX_VALUE + 1wraps to a negative number. UseMath.addExact,subtractExact,multiplyExact,incrementExact,toIntExactand friends when overflow must be an error; they throwArithmeticExceptionwith the messageinteger overfloworlong 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 aRoundingMode, or aMathContext.BigIntegerthrowsBigInteger divide by zerofor division by zero andBigInteger: modulus not positiveformodwith 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 / -1does not throw; it overflows and returnsInteger.MIN_VALUE.Math.divideExactreports it.- Floating-point checks: use
Double.isNaN(),Double.isInfinite()orDouble.isFinite()to detect the non-throwing cases.