Go

Fix Go "panic: runtime error: integer divide by zero" — Variable Divisors, the Constant-Divisor Compile Error, Modulo, and the Empty Average

This panic means an integer division ran with nothing to divide by: the divisor held zero when the division executed. Each section below takes one shape — the smallest variable divisor, the remainder form of the same rule, the constant divisor the compiler stops first, the empty-slice average that produces a zero divisor honestly, the unsigned form, the floating-point contrast, and the one overflow case that does not panic — shows the exact output it prints, and gives the guard or the empty check that keeps the division from running with a zero divisor.

Written November 20, 2026 · Tested with Go 1.26.4 · 7 min read

By the end of this guide
  • The first failure: a variable divisor that is zero
  • Reading the message: a runtime error, not a signal
  • The constant divisor: the compiler stops it first
  • The remainder form: % panics on the same divisor

What this guide is

panic: runtime error: integer divide by zero is a run-time panic: the program built, started, and then divided an integer by zero. The specification states the rule in the integer operators section, in two halves. If the divisor is a constant, it must not be zero. If the divisor is zero at run time, a run-time panic occurs. The same section defines the pair the operators produce: for integers x and y, the quotient q = x / y and the remainder r = x % y satisfy x = q*y + r with |r| < |y|, and x / y is truncated towards zero. A zero divisor breaks that definition outright, because no quotient and remainder can satisfy it, so the runtime stops the program at the division instead of inventing a result.

The word integer in the panic text is load-bearing. The rule covers the signed integer types and the unsigned integer types, and it covers both / and %, because the remainder needs the same divisor the quotient needs. It does not cover floating-point division, which follows the IEEE 754 standard instead and, in the implementation used here, produces an infinity or a NaN value rather than a panic. Most of the shapes in this guide are about where a zero divisor comes from in real code: a count that can be zero, a length of a slice that can be empty, a value read or computed upstream that nobody checked. The division line in the trace is where the panic fires. The defect is wherever the zero was allowed to travel to that line.

The examples here use Go 1.26.4. Every example lives in a single file named main.go inside one module, created once from an empty directory:

Terminal
$ mkdir divzero
$ cd divzero
$ go mod init example.com/divzero
go: creating new go.mod: module example.com/divzero

Each program that follows replaces the contents of that main.go. The panic transcripts are shown as printed by go run -trimpath main.go: the -trimpath flag only changes how file positions print in the trace — ./main.go:8 here, where a plain run prints the same line number behind the full directory path on your machine. Tested with Go 1.26.4.

The first failure: a variable divisor that is zero

The smallest program that earns the panic divides by a variable that holds zero:

Go
// main.go
package main

import "fmt"

func main() {
    n := 10
    d := 0
    fmt.Println(n / d)
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9
exit status 2

The compiler accepts this program because d is a variable: its value is a run-time fact, and the check belongs to the run. At the division on line 8 the divisor is zero, the runtime raises the panic, and the after line never prints. In working code d is rarely a literal zero assigned one line earlier. It is a count of items processed, a number of workers, a difference between two timestamps, or the length of a list that turned out to be empty. The shape is the same in each case: a value that is usually positive reaches a division on the one run where it is zero, and nothing between its source and the division tested for that case.

The repair at this size is a guard on the divisor at the division, or a check at the point where the value is produced. Which one is right depends on what a zero divisor means in the program. If zero is a legitimate state, such as no items to average, the code needs a branch that handles that state and gives it a defined result. If zero signals a defect upstream, the check belongs where the value is made, so the failure names the real cause instead of surfacing later as an arithmetic panic in unrelated code.

Reading the message: a runtime error, not a signal

The panic text carries the prefix runtime error: because the runtime raised it, the same prefix the index out of range and nil pointer panics carry. There is no SIGSEGV line: no memory access failed, so there is no signal report and no pc= address, only the panic, a blank line, and the trace. The trace names the function and the line where the division stands, with the offset of the division instruction in that function. Read the trace line as the statement that broke the rule, not as the place where the bug lives. The bug is wherever the divisor got its zero: an empty input, a counter that never advanced, or a configuration value that was never set. The fixes in this guide are ranked by how close they sit to that source.

One more reading point matters for the shape where the division sits inside a helper. When the dividing function is small enough to be inlined into its caller, the trace shows the helper's frame in the form main.average(...) with the line of the division and no offset, followed by the caller's frame with the line of the call. The average program below prints exactly that form. The division line is still the first line in the trace; the inlining changes how the frame is written, not which statement panicked.

The constant divisor: the compiler stops it first

Write the zero as a constant and the program never runs at all:

Go
// main.go
package main

import "fmt"

func main() {
    fmt.Println(10 / 0)
}
Terminal
$ go run -trimpath main.go
# command-line-arguments
./main.go:6:19: invalid operation: division by zero

This is a compile error, not a panic, and the output has a different shape: no goroutine trace, no exit status line, just the position and the message. The specification covers constant expressions separately from the run-time rule: the divisor of a constant division or remainder operation must not be zero. The compiler evaluates constant expressions while it builds the program, so it meets the zero divisor itself and rejects the code. The same applies to a constant remainder, and to a divisor built from constants, such as a named constant or a constant expression that works out to zero.

The contrast between the two programs is the whole diagnostic value of this section. A division by zero reported by the compiler means the zero was visible in the source, and the fix is to correct the expression. The run-time panic means the zero arrived in a variable, and the fix is a guard or an upstream check. A program can also move between the two: a divisor that starts as a variable and is later replaced by a constant zero during a cleanup turns a latent panic into a build failure, which is the better failure of the two, because it fires on every build instead of on one unlucky run.

The remainder form: % panics on the same divisor

The remainder operator needs the divisor for the same reason the quotient does, and it panics with the same text:

Go
// main.go
package main

import "fmt"

func main() {
    n := 10
    d := 0
    fmt.Println(n % d)
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9
exit status 2

Nothing in the text tells you which operator fired; both print integer divide by zero, and the line number in the trace is how you tell a remainder site from a division site. This matters in code that uses the remainder for bucketing, rotation, or page arithmetic, where the divisor is a bucket count, a cycle length, or a page size. Those values are often settings or derived counts rather than literals, and each one is a divisor in the sense of this guide even though no / appears near it. A guard written only around visible divisions misses the remainder sites, so the audit in the checklist covers both operators.

The honest shape: an average of an empty slice

Most real occurrences of this panic do not contain a variable named as a divisor at all. The divisor is a length:

Go
// main.go
package main

import "fmt"

func average(values []int) int {
    sum := 0
    for _, v := range values {
        sum += v
    }
    return sum / len(values)
}

func main() {
    fmt.Println(average(nil))
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.average(...)
    ./main.go:10
main.main()
    ./main.go:14 +0xa
exit status 2

An empty slice is a normal value, not an error: average(nil) is a call a caller can make by accident whenever a filter, a query, or a read returns nothing. The loop runs zero times, the sum stays zero, and then the return divides by len(values), which is zero because there is nothing to average. The trace shows the inlined frame form described earlier: main.average(...) at line 10, the return statement, with no offset, and the caller at line 14 with its offset. The defect here is a missing case in the function's contract. An average of no values has no integer result, so the function has to say what it does with empty input: return an error, return a second value that reports emptiness, or document that callers must pass at least one value and check that condition at the call sites. Of those, returning an error or a presence flag keeps the check in the one place that knows the input, which is why the fixed program at the end of this guide uses that form.

The same shape appears wherever a total is divided by a count of the things that produced it: a mean latency divided by a request count, a per-file size divided by a file count, a success rate divided by an attempt count. In each case the count is a length or a counter that can be zero on the empty run, and the empty run is usually the first run, the quiet run, or the run after a failure upstream emptied the input. Guarding the division is not defensive decoration in these programs; it is handling the one input the arithmetic does not define.

The unsigned form: no negative values, same panic

Unsigned integers cannot hold a negative divisor, and that changes nothing about zero:

Go
// main.go
package main

import "fmt"

func main() {
    var n uint = 10
    var d uint = 0
    fmt.Println(n / d)
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
panic: runtime error: integer divide by zero

goroutine 1 [running]:
main.main()
    ./main.go:8 +0x9
exit status 2

The specification states the run-time rule for integer values without separating signed from unsigned, and the printed text is identical. Unsigned divisors appear in size arithmetic, capacity calculations, and counts converted from lengths, and a conversion does not remove the zero case: a length of zero converts to an unsigned zero. Code that divides by a value converted from a length or a size carries the same obligation as code that divides by a signed count, and the guard is the same comparison against zero, written on the value before or after the conversion.

The floating-point contrast: no panic, three other results

Divide floating-point values by zero and the program runs to completion:

Go
// main.go
package main

import "fmt"

func main() {
    zero := 0.0
    fmt.Println(10.0 / zero)
    fmt.Println(-10.0 / zero)
    fmt.Println(zero / zero)
}
Terminal
$ go run -trimpath main.go
+Inf
-Inf
NaN

A positive value divided by a floating-point zero gives positive infinity, a negative value gives negative infinity, and zero divided by zero gives NaN, the not-a-number value. The specification does not give floating-point division by zero the integer rule: it says the result is not specified beyond the IEEE 754 standard, and whether a run-time panic occurs is implementation-specific. In this implementation it does not panic, and the three values above are what it prints. Two practical consequences follow. First, a program converted from integer to floating-point arithmetic to dodge this panic has traded a loud stop for values that travel: an infinity or a NaN flows into later arithmetic and comparisons and can surface far from the division, as a wrong total or a comparison that is false in every direction, because NaN is not equal to anything, including itself. Second, a mixed program can show both behaviors in one run: the integer divisions panic, the floating-point divisions print infinities, and the difference is the types at the division, not the values.

The one overflow case that does not panic: the most negative value divided by -1

Integer overflow in Go wraps rather than panicking, and division has one case where that rule shows:

Go
// main.go
package main

import (
    "fmt"
    "math"
)

func main() {
    x := math.MinInt
    fmt.Println(x / -1)
    fmt.Println(x % -1)
}
Terminal
$ go run -trimpath main.go
-9223372036854775808
0

The most negative value of a signed integer type has no positive counterpart at the same width, so dividing it by -1 cannot produce the mathematical result. The specification names this as the one exception to the quotient and remainder relationships: if the dividend is the most negative value for its type, the quotient is equal to the dividend itself, and the remainder is 0, due to two's-complement integer overflow. On this machine int is 64 bits wide, so the value is -9223372036854775808, and the program prints that value and then 0. This case earns its place in the guide because it looks like a division defect when it is found in output — a negative average, a sign that never flips — and it is not one: it is defined behavior, and the repair, where the result matters, is to widen the arithmetic to a larger type before dividing, not to guard the divisor, which is -1 and entirely legal.

The contrast: a panic can be recovered

This panic is an ordinary panic once the runtime raises it, and a deferred recover catches it:

Go
// main.go
package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered:", r)
        }
    }()
    n := 10
    d := 0
    fmt.Println(n / d)
    fmt.Println("after")
}
Terminal
$ go run -trimpath main.go
recovered: runtime error: integer divide by zero

The deferred function prints the recovered value, which carries the runtime error: prefix as part of the value's text, and the program exits cleanly; after does not print, because the panic still unwound the function that raised it. Recovering is a legitimate pattern at a boundary, around work the program does not control, and as a probe that confirms which division in a suspect path fires first. Around the program's own arithmetic it is the wrong tool: it converts a missing guard into an unwinding, discards whatever the function was in the middle of, and leaves the zero divisor free to arrive again on the next call. The guard is cheaper than the recovery in every way that matters — it runs before the division, it keeps the surrounding work, and it can name the actual cause, an empty input or a zero count, instead of the arithmetic symptom.

The fixed program

One program that applies the fixes at once: the division returns an error on a zero divisor instead of panicking, and the average reports empty input as an error instead of dividing by a zero length:

Go
// main.go
package main

import (
    "errors"
    "fmt"
)

func divide(n, d int) (int, error) {
    if d == 0 {
        return 0, errors.New("division by zero")
    }
    return n / d, nil
}

func average(values []int) (int, error) {
    if len(values) == 0 {
        return 0, errors.New("no values")
    }
    sum := 0
    for _, v := range values {
        sum += v
    }
    return sum / len(values), nil
}

func main() {
    q, err := divide(10, 0)
    fmt.Println(q, err)
    q, err = divide(10, 3)
    fmt.Println(q, err)
    a, err := average(nil)
    fmt.Println(a, err)
    a, err = average([]int{2, 4, 6})
    fmt.Println(a, err)
}
Terminal
$ go run main.go
0 division by zero
3 <nil>
0 no values
4 <nil>

Each function checks its divisor in the form that fits it. divide tests the divisor itself, because the divisor is its parameter and zero is never a value it can use. average tests the length before the loop, because the length is the divisor and because empty input is a fact about the call that the caller can act on. Both return the error as a value the caller prints and handles, and the successful calls show the arithmetic unchanged: 10 divided by 3 is 3, truncated towards zero as the specification defines integer division, and the average of 2, 4, and 6 is 4. Nothing recovers and nothing needs to: every division in the program runs only after its divisor is known to be non-zero.

The fixes, ranked

Check the divisor where the division lives, and return the failure as a value. A function that divides by a parameter or by a length tests that value first and returns an error, or a presence flag, when it is zero. This is ranked first because it covers every caller, names the cause at the site that knows it, and turns a panic that unwinds the program into a value the caller already has to handle.

Handle the empty case as a case, not as an accident. Where the divisor is a count or a length, empty input is a state the program will meet — on the first run, the quiet run, and the run after an upstream failure. Decide what the result is for that state at the function that owns the arithmetic: an error, a defined zero with a flag, or a documented precondition checked by callers. An undecided empty case is a panic waiting for its run.

Check the value where it is produced when zero means an upstream defect. Some divisors are zero only when something else went wrong: a counter that should have advanced, a size that should have been set. A guard at the division keeps the program alive, but the check that finds the defect sits at the source, and both belong in the program — the source check to report the cause, the division guard to keep a missed case from becoming a panic.

Audit remainder sites with the division sites. The % operator panics on the same zero with the same text. Bucket counts, cycle lengths, and page sizes are divisors, and a fix pass that reads only / leaves them in place.

Do not convert to floating-point arithmetic to dodge the panic. The conversion trades a stop at the division for infinity and NaN values that travel into later arithmetic and comparisons. Where floating-point results are the right tool, test for them deliberately with the math package's infinity and NaN checks; never use the type change as a guard.

Do not answer the panic with recover in code that owns the division. The recovered program above is a probe and a boundary pattern. Around your own divisions, recover converts a missing guard into an unwinding, and the zero divisor survives to fire again.

Which fix for which cause

What the message and code show Cause Fix
panic: runtime error: integer divide by zero at a division by a variable The divisor arrived as zero from input, a count, or a computed value Guard the divisor at the division; return an error or a flag
The same panic at a division by len(...) or a counter The input was empty or the count never advanced Handle the empty case in the owning function; check the count at its source
The same panic at a % expression A bucket count, cycle length, or page size is zero Guard the remainder's divisor with the division sites
The same panic with an unsigned divisor A size or length converted to an unsigned type is zero Test the value against zero before or after the conversion
invalid operation: division by zero from the compiler, with a position instead of a trace The divisor is a constant zero or a constant expression that works out to zero Correct the constant expression in the source
No panic, and the output holds +Inf, -Inf, or NaN The division is floating-point, so a zero divisor produces those values instead Test the divisor before dividing, or test the result with the math package's checks
No panic, and a division by -1 returns the most negative value unchanged The dividend is the most negative value of its type, and the result cannot be represented Widen the arithmetic to a larger type before dividing

Checklist

  • Read the operator at the trace line: / and % panic with the same text, and the line is how you tell which site fired.
  • Follow the divisor back to its source: a parameter, a length, a counter, a setting, or a value read from outside the program. The fix belongs at the division and, where zero means a defect, at that source too.
  • List every division and remainder whose divisor is not a non-zero constant, and confirm each one has a guard, an error return, or a caller-side precondition that is actually checked.
  • Test the empty input for every function that divides by a length or a count: an empty slice, an empty result set, and a first run with nothing processed.
  • Check converted divisors: a length or size converted to an unsigned or a narrower type keeps its zero case through the conversion.
  • Where a program mixes integer and floating-point division, confirm the floating-point results are tested for infinity and NaN instead of being trusted because no panic fired.

Sources

  • The Go Programming Language Specification — for integer operators (the quotient and remainder relationships with division truncated towards zero, the exception under which the most negative value divided by -1 gives that value itself with a remainder of 0, a constant divisor must not be zero, and a divisor that is zero at run time causes a run-time panic), for constant expressions (the divisor of a constant division or remainder operation must not be zero), for floating-point operators (the result of a floating-point division by zero is not specified beyond the IEEE 754 standard, and whether a run-time panic occurs is implementation-specific), and for signed integer overflow (the operations may legally overflow and the resulting value is deterministically defined, so overflow does not cause a run-time panic).

Keep Exploring