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 ?

1

2 Answers 2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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);
    }
}

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.