How to handle Java ArithmeticException?
- You should make sure the divisor isn't zero (0) before attempting any division.
- You can handle the ArithmeticException using Java try and catch blocks.
Make sure the divisor isn't zero (0)
When you try the following Java code JVM throws ArithmeticException.
int x=100,y=0;
int z= x/y;
Output:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
So, you should make sure the divisor isn't zero (0) before attempting any division. This usually means validating the value of the divisor before using it.
public class Main {
public static void main(String[] args) {
int x=100,y=0;
if(y!=0){
int z= x/y;
System.out.println("Result : " + z);
}else{
System.out.println("undefined (division by zero)");
}
}
}
Using Java try and catch blocks
The other option to handle Java ArithmeticException is using try and catch blocks. This means that surround the statements that can throw ArithmeticException with try and catch blocks. So, you can Catch the ArithmeticException and take necessary action for your program, as the execution doesn't abort.
public class Main {
public static void main(String[] args) {
int x=100,y=0;
try {
int z= x/y;
System.out.println("Result : " + z);
} catch (ArithmeticException e) {
System.out.println("Handle ArithmeticException here...");
}
}
}
What is Java ArithmeticException?
Arithmetic exceptions are raised during run time by Java Virtual Machine when you try to perform any arithmetic operation which is not possible in mathematics.
When an Arithmetic Exception Occurs in Java?
- An integer "divide by zero" throws ArithmeticException.
- When a big-decimal (non terminating decimal number) is divided by another big-decimal number.
Related Topics
- Reached end of file while parsing
- Unreachable statement error in Java
- Int Cannot Be Dereferenced Error - Java
- How to fix java.lang.classcastexception
- How to fix java.util.NoSuchElementException
- How to fix "illegal start of expression" error
- How to resolve java.net.SocketException: Connection reset
- Non-static variable cannot be referenced from a static context
- Error: Could not find or load main class in Java
- How to Handle OutOfMemoryError in Java
- How to resolve java.net.SocketTimeoutException