Divided by zero
1. What is Division by Zero in Java?
-
Integer division by zero (e.g.,
10 / 0
) causes an error. -
Java throws:
ArithmeticException: / by zero
β 2. Without Handling (Bad Way)
Output:Exception in thread "main" java.lang.ArithmeticException: / by zero
β 3. With Exception Handling (Good Way)
πΉ Steps:
-
Use
try
block for risky code. -
Use
catch
block to handle the error.
Output:Cannot divide by zero.
β 4. Optional: Check Before Dividing
int a = 10;
int b = 0;
if (b != 0) {
int result = a / b;
System.out.println(“Result: ” + result);
} else {
System.out.println(“Division not allowed: b is zero.”);
}