Ad Space — Top Banner

integer divide by zero

Go Programming Language

Severity: Critical

What Does This Error Mean?

Go panics immediately when you divide an integer by zero. This is a runtime error — it crashes your program. Float division by zero does not panic — it returns Inf or NaN instead.

Affected Models

  • Go 1.21
  • Go 1.22
  • Go 1.23
  • Go 1.24

Common Causes

  • Dividing by a variable that can be zero without checking it first
  • Computing a percentage or average with a zero denominator
  • A function argument that defaults to zero when not provided
  • An integer parsed from user input or config that is zero
  • A counter or length value that is zero when no items exist

How to Fix It

  1. Add a check before every division: if divisor == 0 { handle the error or return }

    This is the fundamental fix. Never divide without first confirming the denominator is non-zero.

  2. Return an error from your function instead of panicking.

    if b == 0 { return 0, fmt.Errorf("division by zero") } — let the caller decide how to handle it.

  3. For averages or percentages, check if the total count is zero before dividing.

    if count == 0 { return 0 } — returning zero is often the right default for an empty dataset.

  4. Validate inputs at the boundary of your program — parse, validate, then compute.

    If the divisor comes from a config file, database, or API, validate it before using it in math.

  5. Use float64 if you need division that can safely produce Inf or NaN instead of panicking.

    var a, b float64; result := a / b — if b is 0.0, result is +Inf, not a panic. Check math.IsInf() and math.IsNaN() afterward.

When to Call a Professional

Division by zero usually indicates a logic error in your calculations. If it occurs in financial, scientific, or safety-critical code, have a senior developer review the mathematical logic.

Frequently Asked Questions

Why does float division by zero not panic in Go?

The IEEE 754 floating-point standard defines Inf and NaN as valid results for division by zero. Go follows this standard for float64 and float32. Integers have no Inf value, so Go panics instead.

Can I catch a division by zero panic with recover()?

Yes — recover() in a deferred function will catch this panic. But using recover() as a substitute for a proper nil/zero check is bad practice. Fix the root cause instead.

Does the Go compiler catch division by zero at compile time?

Only for constant expressions — e.g., const x = 1 / 0 will fail to compile. If the divisor is a variable, the compiler cannot detect it. You must add the runtime check yourself.