Java Program for Div Zero Exception

Program

public class DivZero {
    public static void main(String[] args){
        int a, b;
        a = 10;
        b = 0;
        System.out.println(a/b);
    }
}

This Java program demonstrates an ArithmeticException: Division by Zero, which occurs when a number is divided by zero.

  1. Variables a and b:

    • The program declares two integers, a and b.
    • a is assigned a value of 10.
    • b is assigned a value of 0.
  2. Division Operation (a / b):

    • The program attempts to divide a by b using the statement System.out.println(a/b);.
    • Since dividing a number by zero is mathematically undefined, Java throws an ArithmeticException.
  3. No Exception Handling:

    • This program does not include any error-handling mechanism (e.g., try-catch block).
    • As a result, the program terminates abnormally and prints an error message.
  4. ArithmeticException:

    • This is a runtime exception in Java.
    • It occurs when an invalid arithmetic operation (e.g., division by zero) is performed.

Output

Exception in thread "main" java.lang.ArithmeticException: / by zero
        at ThrowDivZero.main(ThrowDivZero.java:6)

  • The exception message indicates:
    • ArithmeticException is the type of error.
    • The error occurs at line 6 (System.out.println(a/b);).
    • The reason is division by zero (/ by zero).