ArithmeticException
Thrown on an invalid arithmetic operation, such as integer division by zero.
Available since: Java 1.0
Syntax
public class ArithmeticException extends RuntimeExceptionExamples
Division by zero: integers and doubles:
void main() {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
IO.println(e.getMessage());
}
IO.println(10.0 / 0);
}Output:
/ by zero
InfinityOverflow with Math.addExact():
void main() {
try {
Math.addExact(Integer.MAX_VALUE, 1);
} catch (ArithmeticException e) {
IO.println(e.getMessage());
}
}Output:
integer overflowNotes
Dividing a double by zero does not throw but gives Infinity or NaN. Ordinary int overflow is silent too; to get an exception use Math.addExact(), Math.multiplyExact(). It is better to check the divisor up front than to catch this exception.
See also
- RuntimeException — The base class of unchecked exceptions — bugs in program logic.
- NumberFormatException — Thrown when a string cannot be converted to a number.
Related recipes
In the tutorial
- What exceptions are — Exceptions in Java — how a program reports an error, how to read a stack trace, common exceptions and the Throwable hierarchy.