integer divide by zero

Go Programming Language

Severity: Moderate

What it means

The full message: panic: runtime error: integer divide by zero. The % operator panics the same way.
The Go spec: if the divisor is zero at run time, a run-time panic occurs.
A constant zero divisor doesn't compile at all: the compiler says invalid operation: division by zero.

Affected Models

  • Go programs at run time

How to Fix It

  1. Find the first line of your own code in the stack trace, and the divisor on it.

  2. Check it before dividing, and decide what the answer should be with nothing to divide by: if n == 0 { return 0, false }

  3. A value from user input, a file or another service? Check it where it comes in, and report a clear error there.

Frequently Asked Questions

Why doesn't a float64 divided by zero panic?

The Go spec leaves floating-point division by zero to the IEEE 754 standard, and says whether it panics is up to the implementation.
Check the result with math.IsInf and math.IsNaN.