[Solved] java.lang.ArithmeticException: / by zero in JAVA

java.lang.ArithmeticException is Unchecked exception and sub class of java.lang.RuntimeException. It’s thrown when an exceptional condition occurred in Arithmetic Operations. It can also occurred by virtual machine as if suppression were disabled and /or the stack trace was not writable.

Constructors:

  • ArithmeticException() : Constructs an ArithmeticException with no detail message.
  • ArithmeticException(String s) : Constructs an ArithmeticException with the specified detail message.
Example :
An integer value “divide by zero” throw ArithmaticException.  In below example i am dividing int, double, float and long value with 0. For long and int type value it’s throwing Arithmatic Exception while for double and float printing special value as Infinity.  See below How to fix Arithmetic Exception? section.
package example;

public class ArithmaticExceptionExample {

public static void main(String[] args) {
int x=0;
int y=5;
double z=6;
float l=6;
long k=10L;
//Integer value divide by integer value as 0 throw ArithmeticException
try
{
System.out.println("Integer value divide by zero");
System.out.println(y/x);
}
catch(ArithmeticException ex)
{
ex.printStackTrace();
}
//Double value divide by integer value as 0 No Exception special value Infinity
System.out.println("Double value divide by zero");
System.out.println(z/x);

//Float value divide by integer value as 0 No Exception special value Infinity
System.out.println("Float value divide by zero");
System.out.println(l/x);

//Long value divide by integer value as 0 throw ArithmeticException
try
{
System.out.println("Long value divide by zero");
System.out.println(k/x);
}
catch(ArithmeticException ex)
{
ex.printStackTrace();
}

}

}

Output:

Integer value divide by zero
java.lang.ArithmeticException: / by zero
at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:15)
Double value divide by zero
Infinity
Float value divide by zero
Infinity
Long value divide by zero
java.lang.ArithmeticException: / by zero
at example.ArithmaticExceptionExample.main(ArithmaticExceptionExample.java:31)

How to fix Arithmetic Exception?

In above example:

Y/X or K/X result ArithmeticException

What happens here is that since both the dividend and the divisor are int, the operation is an integer division, whose result is rounded to an int. Remember that an int can only contain whole number (of limited range, some 4 billion numbers approximately) That’ s why throwing Arithmatic Exception. same case for long value.

Z/X or L/X result special value Infinity

Here float (L) or double (X) precision value  divide by zero store in float and double value that why result is special value Infinity.

 

3 thoughts on “[Solved] java.lang.ArithmeticException: / by zero in JAVA”