liveBook · Manning

Panic

As explained in Go in Action, Second Edition

A panic is Go's runtime mechanism for terminating ordinary execution and reporting an unrecoverable run-time error unless recovered.

A panic interrupts ordinary control flow when something has gone seriously wrong. Go can trigger one at runtime: indexing a slice past its length stops the program and reports an index-out-of-range error. Code can also call panic(any) to report a value and provide a code path to the call. section 4.2.8 section 7.4

Prevent predictable panics rather than using them for routine error handling. If a function requires three slice entries, check len before indexing and return an error when the requirement is unmet. If it can accept any number of entries, a range loop avoids those fixed indices altogether. section 4.2.8

Missing command-line argument

os.Args includes the program name, so reading os.Args[1] without an additional argument panics. Check `len(os.Args) < 2` first; then report that a filename is needed instead of attempting the invalid access. section 2.7.2

Reserve an explicit panic for a truly exceptional condition that cannot reasonably be handled without terminating the program. If callers might encounter the condition, return an error instead. Document any deliberate panic in the function’s godoc comment. recover may contain a sporadic panic temporarily, but finding and fixing its cause is usually the better response. section 7.12.1 section 7.13

Listing 4.59 Using a range statement Instead of explicit indices
func printMedalists3(raceName string, contestants []string) {
	fmt.Printf("Results for %s:\n", raceName)
	for place, contestant := range contestants {
		switch place {
		case 0:
			fmt.Printf("Gold Medal: %s\n", contestant)
		case 1:
			fmt.Printf("Silver Medal: %s\n", contestant)
		case 2:
			fmt.Printf("Bronze Medal: %s\n", contestant)
		default:
			fmt.Printf("Finisher: %s\n", contestant)
			// or just return
		}
	}
}

func main() {
	race1 := []string{"Sally", "Steve", "Jo", "Adam"}
	race2 := []string{"Jon", "Jen"}
	race3 := []string{}

	printMedalists3("Race 1", race1)
	// Race 2 only has two contestants, but we still need to list them!
	printMedalists3("Race 2", race2)
	// Throw in a race with no contestants at all.
	printMedalists3("Race 3", race3)
}

The range-based race-results function handles short and empty slices without indexing entries that might not exist. section 4.2.8

How Go in Action, Second Edition covers it

How deep it goes
Explains runtime bounds failures, prevention, and criteria for explicit panic; treats recover briefly rather than developing recovery mechanics.
Examples
Shows missing command-line arguments and a race-results function that panics on a short slice, then uses len or range.
What it assumes
Assumes basic Go function and slice usage while demonstrating how len checks and returned errors prevent invalid indexing.
What you can do after
Diagnose/debug with it by recognizing bounds panics, guarding predictable failures, and choosing returned errors over deliberate panics.
How it connects
Connects panic to slices, len, range loops, returned errors, recover, and os.Exit.

Also explained in

Compare how 8 books explain panic →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.