1

Below is my code :

public class prg34 {
    public static void main(String[] args) {
        int a=6;
        for(int i=0;i<10;i++){
            System.out.println(a/i);
        }
    }
}

Exception:

Exception in thread "main" java.lang.ArithmeticException: / by zero at run.prg34.main(prg34.java:8)

How to solve above Arithmetic Exception in java ?

LuFFy
  • 8,799
  • 10
  • 41
  • 59
  • Possible duplicate: https://stackoverflow.com/questions/14137989/java-division-by-zero-doesnt-throw-an-arithmeticexception-why/14138002 – sɐunıɔןɐqɐp Jun 12 '18 at 07:22

2 Answers2

1

You are trying to divide by zero in your first iteration. Change your first condition of i = 0, to something other than zero.

You cannot divide by 0, as I believe Java handles the division by zero error by a processor exception which triggers an interrupt.

Your first iteration is trying 6/0.

public static void main(String[] args) {
    int a=6;
    for(int i=1;i<10;i++){
        System.out.println(a/i);
    }
}
Jesse
  • 1,814
  • 1
  • 21
  • 25
0

The first loop in your code gives an exception because you are trying to divide 6 by 0 i.e the ArithmeticException.

In order to fix this you must have to use try catch block. I've illustrated full code here. Please fix this.

public class prg34 {
public static void main(String[] args) {
    int a=6;
    try {
        for(int i = 0; i < 10; i++) {
            System.out.println(a/i);
        }
    }catch(ArithmeticException e) {
        System.out.println("Division by zero is not possible. "+ e);
    }
}

}

N.Neupane
  • 281
  • 1
  • 4
  • 17