Arithmetic Exception in Java
The Exception Handling is one of the most powerful mechanisms to handle the runtime errors so that the normal flow of the application can be maintained. In Java, exception is an abnormal condition. Java programming language defines various exceptions. In this section, we will discuss the one of the prominent exceptions that is ArithmeticException in Java.
The arithmetic exception is a type of unusual outcome or unchecked error of the code, which is thrown or raised whenever a wrong mathematical or arithmetic operation appears in the code during run time. A runtime issue, also called an exception, appears whenever the denominator of a fraction is 0, and the JVM is not able to find out the result; hence the program execution is terminated, and an exception is raised. Note that at the point where the exception has been raised, the program terminates. However, the code earlier than that is executed, and the appropriate result is displayed.
Arithmetic Exception Structure
The arithmetic exception base class is java.lang.ArithmeticException, which is the child class of java.lang.RuntimeException, which in turn is the child class of java.lang.Exception.
Arithmetic Exception Constructor
How Arithmetic Exception Occurrence?
The following are two situations where the arithmetic exception may occur.
Divide By 0
Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticException.divide(ArithmeticException.java:6) at ArithmeticException.main(ArithmeticException.java:16)
Non-Terminating Big Decimal
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result. at java.base/java.math.BigDecimal.divide(BigDecimal.java:1766) at ArithmeticException1.main(ArithmeticException1.java:9)
Explanation: In the above program, the Big Decimal class does not know the exact output, which comes after division, to display. It is because the output is non-terminating decimal expansion. One approach to solve it is to provide the limit. For example, we can tell explicitly in the program that the output should be limited to 6 decimal places. Observe the following program.
Handling Arithmetic Exception
We can handle the arithmetic exception on our own using the try-catch block. Observe the following programs.
Should avoid dividing by 0 java.lang.ArithmeticException: / by zero
For non-terminating decimal expansion, all we have to do is to wrap the line where division is occurring inside the try block.
Should avoid dividing by an integer that leads to non-terminating decimal expansion. java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.