
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Handle ArithmeticException Unchecked in Java
Java ArithmeticException
The ArithmeticException of java.lang package is an unchecked exception in Java. It is raised when an attempt is made to use a wrong mathematical expression in the Java program. An example of ArithmeticExeption is division by 0. If you divide two numbers and the number in the denominator is zero. The Java Virtual Machine will throw ArithmeticException.
Example: Throwing ArithmeticException
In the following Java program, we try a mathematical operation where we divide a number by 0.
public class ArithmeticExceptionTest { public static void main(String[] args) { int a = 0, b = 10; int c = b/a; System.out.println("Value of c is : "+ c); } }
Output
In the above example, ArithmeticExeption is occurred because the denominator value is zero.
Exception in thread "main" java.lang.ArithmeticException: / by zero at ArithmeticExceptionTest.main(ArithmeticExceptionTest.java:5)
How to handle ArithmeticException?
Like any other exception, you can handle the ArithmeticException using try and catch blocks. When an exception occurs within try block, the execution moves to corresponding catch block. It executes the statement in the catch block and continues with the statement present after the try and catch blocks.
Apart from using try-catch blocks for runtime errors, there are a few steps additional steps that we can take to avoid ArithmeticException, which are:
- Use if-else block within try block to check whether the operands are valid.
- Use built-in mathematical methods of Java to handle the decimal places.
- Do not use two big decimal numbers as operands in division operation because the result cannot be displayed in a finite number of decimal places.
Example: Handling ArithmeticExeption
In the following program, we are using if-else block within try block to check whether the denominator is greater than 0.
public class ArithmeticExceptionTest { public static void main(String[] args) { int a = 0, b = 10; int c = 0; try { // Check if denominator is not zero if (a != 0) { c = b / a; } else { System.out.println("Denominator is zero!"); } } catch (ArithmeticException e) { e.printStackTrace(); System.out.println("ArithmeticException is handled. But take care of the variable "c""); } System.out.println("Value of c: " + c); } }
Output
Since the denominator is 0, the else block inside try block will be executed as you can see below:
Denominator is zero! Value of c: 0