Handling Division 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.
Key Concepts
Approach 3: Java 8
import java.util.Optional;
public class DivideByZeroOptional {
public static void main(String[] args) {
int a = 10, b = 0;
// Builds a present Optional only when the division is safe to perform
Optional<Integer> result = b != 0 ? Optional.of(a / b) : Optional.empty();
System.out.println(result.map(r -> "Result: " + r).orElse("Error: Cannot divide by zero"));
System.out.println("Execution finished");
}
}
Output
Core Logic
Optional can represent 'a result, or nothing' directly — build one only when the division is safe, and let map()/orElse() handle both outcomes without a try-catch or if-else.
- 1
b != 0 ? Optional.of(a / b) : Optional.empty()builds a presentOptionalholding the quotient when it's safe, or an empty one whenbis zero — mirroring the defensive check's condition without the branching statements. - 2
.map(r -> "Result: " + r)only runs if theOptionalis present, formatting the successful result. - 3
.orElse("Error: Cannot divide by zero")supplies the fallback message if theOptionalwas empty, without ever touching the risky division. - 4
"Execution finished"still prints unconditionally afterward, in place of thefinallyblock.
b = 0, the ternary produces Optional.empty(), so .map() is skipped and .orElse(...) supplies "Error: Cannot divide by zero".Key Point: Optional makes 'this might not have a value' part of the type itself — the same idea as the defensive check, just expressed as a value that flows through map()/orElse() instead of an if/else branch.
Key Concepts
Interview Questions
Why does 10 / 0 throw but 10.0 / 0 doesn't?
Integer division by zero has no valid result, so it throws ArithmeticException. Floating-point arithmetic follows the IEEE 754 standard instead and returns Infinity, or NaN for 0.0 / 0.0.
Is checking the divisor better than catching the exception?
Usually, yes. if (b == 0) is clearer and cheaper than letting an exception be thrown and caught, and it makes the special case explicit.