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

  1. Check the divisor before calling: only call divide when b != 0.
  2. Catch ArithmeticException around the call and handle it.
  3. 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

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


AI-assisted analysis of kunal-kushwaha/DSA-Bootcamp-Java@6bc4d8bf8a (2026-08-31). Data as JSON: /api/errors/cc3168bffbabbed7. Report an issue: GitHub.