Cause of the exception
This error occurs when we divided a given number by zero.
package com.logicbig.example.arithmeticexception;
public class ArithmeticExceptionDivideByZero {
public static void main(String... args) {
divide(10, 2);
divide(16, 4);
divide(20, 0);
divide(99, 11);
}
public static void divide(int a, int b) {
int result = a / b;
System.out.printf("%s ÷ %s = %s%n", a, b, result);
}
}
Output
java.lang.ArithmeticException: / by zero
at com.logicbig.example.arithmeticexception.ArithmeticExceptionDivideByZero.divide (ArithmeticExceptionDivideByZero.java:19)
at com.logicbig.example.arithmeticexception.ArithmeticExceptionDivideByZero.main (ArithmeticExceptionDivideByZero.java:14)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0 (Native Method)
at jdk.internal.reflect.NativeMethodAccessorImpl.invoke (NativeMethodAccessorImpl.java:62)
at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke (DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke (Method.java:564)
at org.codehaus.mojo.exec.ExecJavaMojo$1.run (ExecJavaMojo.java:282)
at java.lang.Thread.run (Thread.java:832)
Avoiding the exception
To avoid this error always use a zero check on the divisor:
package com.logicbig.example.arithmeticexception;
public class ArithmeticExceptionDivideByZeroFix {
public static void main(String... args) {
divide(10, 2);
divide(16, 4);
divide(20, 0);
divide(99, 11);
}
public static void divide(int a, int b) {
if (b != 0) {
int result = a / b;
System.out.printf("%s ÷ %s = %s%n", a, b, result);
} else {
System.out.printf("Division cannot be performed by zero number: a=%s, b=%s%n", a, b);
}
}
}
Output
10 ÷ 2 = 5
16 ÷ 4 = 4
Division cannot be performed by zero number: a=20, b=0
99 ÷ 11 = 9