Arithmetic Exception in JavaThe 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 StructureThe 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 0FileName: ArithmeticException.java Output: Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticException.divide(ArithmeticException.java:6) at ArithmeticException.main(ArithmeticException.java:16) NonTerminating Big DecimalFileName: ArithmeticException1.java Output: Exception in thread "main" java.lang.ArithmeticException: Nonterminating 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 nonterminating 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. FileName: ArithmeticException2.java Output: 0.647058 Handling Arithmetic ExceptionWe can handle the arithmetic exception on our own using the trycatch block. Observe the following programs. FileName: HandleArithmeticException.java Output: Should avoid dividing by 0 java.lang.ArithmeticException: / by zero For nonterminating decimal expansion, all we have to do is to wrap the line where division is occurring inside the try block. FileName: HandleArithmeticException1.java Output: Should avoid dividing by an integer that leads to nonterminating decimal expansion. java.lang.ArithmeticException: Nonterminating decimal expansion; no exact representable decimal result.
Next TopicJava instanceof operator
