In this tutorial, we will learn how to fix java.lang.ArithmeticException thrown when JRE finds an exceptional arithmetic operation like divide by zero.
What is java.lang.ArithmeticException?
java.lang.ArithmeticException occurs when java comes over an arithmetic operation that is exceptional. Usually, one would come across “java.lang.ArithmeticException: / by zero” which occurs when an attempt is made to divide two numbers and the number in the denominator is zero.
Let us see a sample program that could produce this exception.
ArithmeticExceptionExample.java
package com.tutorialkart.java;
/**
* @author tutorialkart.com
*/
public class ArithmeticExceptionExample {
public static void main(String[] args) {
int a=0, b=4 ;
int c = b/a;
System.out.println("Value of c : "+c);
}
}
Output
Exception in thread "main" java.lang.ArithmeticException: / by zero
at com.tutorialkart.java.ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:10)
Note: ArithmeticException objects may be constructed by the JVM (Java Virtual Machine). For more information on ArithmeticException, refer the java doc link here.
Let us see "java.lang.ArithmeticException: / by zero" in detail.
- java.lang.ArithmeticException : Exception thrown by Java runtime while trying to execute the statement.
- / by zero : is the detail message given to ArithmeticException class while creating the ArithmeticException object.
How to handle ArithmeticException?
Let us handle the ArithmeticException using try-catch.
- Surround the statements that could throw ArithmeticException with try-catch block.
- Catch ArithmeticException
- Take necessary action for the further course of your program, as the execution doesn't abort.
Example.java
package com.tutorialkart.java;
/**
* @author tutorialkart.com
*/
public class Example {
public static void main(String[] args) {
int a=0, b=4 ;
int c=0;
try {
c = b/a;
} catch (ArithmeticException e) {
e.printStackTrace();
System.out.println("Nothing to worry.\n"
+ "We are just printing the stack trace.\n"
+ "ArithmeticException is handled. But take care of the variable \"c\"");
}
System.out.println("Value of c : "+c);
}
}
Output
java.lang.ArithmeticException: / by zero
at com.tutorialkart.java.ArithmeticExceptionExample.main(ArithmeticExceptionExample.java:12)
Nothing to worry.
We are just printing the stack trace.
ArithmeticException is handled. But take care of the variable "c"
Value of c : 0
When an exception occurs, the execution falls onto the catch block from the point of occurrence of exception. It executes the statement in catch block and continues with the statement present after the try-catch block. So, care has to be taken while handling the exceptions and deciding on the further course of action in your program.
Conclusion
In this Java Tutorial, we have learnt to fix java.lang.ArithmeticException thrown when JRE finds an exceptional arithmetic operation like divide by zero.