kunal-kushwaha/DSA-Bootcamp-Java · error · ArithmeticException
please do no divide by zero
Error message
please do no divide by zero
What it means
The static divide method explicitly throws java.lang.ArithmeticException with a friendly message when the divisor b is 0, guarding the a / b division that would otherwise throw '/ by zero'. The throws ArithmeticException clause is documentation only, since it is unchecked.
Source
Thrown at lectures/17-oop/code/src/com/kunal/exceptionHandling/Main.java:28
String name = "Kunal";
if (name.equals("Kunal")) {
throw new MyException("name is kunal");
}
} catch (MyException e) {
System.out.println(e.getMessage());
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} catch (Exception e) {
System.out.println("normal exception");
} finally {
System.out.println("this will always execute");
}
}
static int divide(int a, int b) throws ArithmeticException{
if (b == 0) {
throw new ArithmeticException("please do no divide by zero");
}
return a / b;
}
}
View on GitHub (pinned to 6bc4d8bf8a)
Solutions
- Check the divisor before calling: only call divide when b != 0.
- Catch ArithmeticException around the call and handle it.
- Return a sentinel/Optional or handle zero explicitly in the calling logic.
Example fix
// before
int r = divide(a, b);
// after
if (b != 0) {
int r = divide(a, b);
} else {
System.out.println("cannot divide by zero");
} Defensive patterns
Strategy: validation
Validate before calling
if (b != 0) {
int r = divide(a, b);
} else {
System.out.println("cannot divide by zero");
} Try / catch
try {
int r = divide(a, b);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
} Prevention
- Always validate divisors are non-zero before division.
- Never pass defaulted/uninitialized values as denominators.
- When averaging, check the collection is non-empty first.
- Catch ArithmeticException at the boundary where user/runtime input enters the calculation.
When it happens
Trigger: Calling divide(a, 0) for any int a; the check is if (b == 0) throw new ArithmeticException("please do no divide by zero").
Common situations: Dividing by a runtime-computed value (user input, counts, averages over empty collections); passing defaulted 0 denominators; computing ratios where totals can be zero.
Related errors
- name is kunal
- Queue is empty
- Queue is empty
- Cannot pop from an empty stack!!
- Cannot peek from an empty stack!!
AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31).
Data as JSON: /api/errors/cc3168bffbabbed7.
Report an issue: GitHub.