Handling Divide by Zero in Java
Problem
Dividing an integer by zero in Java doesn't produce infinity like floating-point math does — it throws an ArithmeticException instead.
Divide two numbers and handle the case where the divisor is zero.
Java Program
public class DivideByZero {
public static void main(String[] args) {
int a = 10, b = 0;
try {
int result = a / b; // throws ArithmeticException when b is 0
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero");
} finally {
// Runs whether or not an exception was thrown
System.out.println("Execution finished");
}
}
}Output
Core Logic
Rather than letting a divide-by-zero crash the program, wrap the risky division in try-catch-finally and handle it gracefully.
- 1The risky division
a / bsits inside atryblock. - 2Integer division by zero throws an
ArithmeticExceptionat runtime — unlike floating-point division, there's no 'Infinity' fallback. - 3The matching
catch (ArithmeticException e)block runs instead of the program crashing, printing an error message. - 4The
finallyblock runs afterward regardless of whether an exception was thrown.
a = 10, b = 0, the program prints "Error: Cannot divide by zero" followed by "Execution finished" from the finally block.Key Point: finally always executes — whether the try block succeeds, throws, or even returns — which makes it the right place for cleanup code.
Key Concepts
Approach 2: Defensive Check (No Exception)
public class DivideByZeroCheck {
public static void main(String[] args) {
int a = 10, b = 0;
// Check the divisor up front instead of relying on an exception
if (b == 0) {
System.out.println("Error: Cannot divide by zero");
} else {
System.out.println("Result: " + (a / b));
}
System.out.println("Execution finished");
}
}
Output
Core Logic
Or skip the exception altogether — check whether the divisor is zero before you divide, instead of cleaning up after the fact.
- 1
if (b == 0)checks the divisor up front, before any division is attempted. - 2If it's zero, the error message is printed directly — the risky
a / bexpression is never even evaluated. - 3Otherwise, the
elsebranch safely performs the division, sincebis now known to be non-zero. - 4
"Execution finished"prints unconditionally afterward, matching thefinallyblock's behavior in the try-catch version.
b = 0, the check catches it immediately and prints "Error: Cannot divide by zero" without ever throwing an exception.Key Point: Exceptions are for exceptional, hard-to-predict failures — when a condition like 'is the divisor zero' is cheap to check in advance, validating first is usually clearer and slightly faster than relying on try-catch for routine control flow.