Panic and Recover
Some mistakes are so serious that Go cannot go on. Reading past the end of a slice is one. Go then panics: it stops the program and prints a message on the error output.
package main
import "fmt"
func main() {
scores := []int{70, 85, 90}
i := 5
fmt.Println("before")
fmt.Println(scores[i])
fmt.Println("after")
}
Output:
before
panic: runtime error: index out of range [5] with length 3
before was printed, then the program stopped. after never appeared. The message says what went wrong: index 5, but the slice has only 3 items. After this first line, Go also prints a list of the function calls that led to the panic, which helps you find the bug. Other panics you may meet are assignment to entry in nil map and integer divide by zero.
Calling panic yourself
You can start a panic with the built-in function panic. Use it for a situation that should never happen if the code is correct:
package main
import "fmt"
func dayName(n int) string {
switch n {
case 1:
return "Monday"
case 2:
return "Tuesday"
}
panic(fmt.Sprintf("bad day number %d", n))
}
func main() {
fmt.Println(dayName(1))
fmt.Println(dayName(9))
}
Output:
Monday
panic: bad day number 9
Deferred calls still run
When a function panics, Go still runs its deferred calls before the program stops:
package main
import "fmt"
func work() {
defer fmt.Println("clean up")
fmt.Println("working")
panic("disk is full")
}
func main() {
work()
}
Output:
working
clean up
panic: disk is full
Stopping a panic with recover
The built-in function recover stops a panic. It only works inside a deferred function. It returns the value that was given to panic, or nil if there was no panic:
package main
import "fmt"
func safeRun() {
defer func() {
r := recover()
if r != nil {
fmt.Println("recovered:", r)
}
}()
fmt.Println("start")
panic("something went wrong")
}
func main() {
safeRun()
fmt.Println("program keeps going")
}
Output:
start
recovered: something went wrong
program keeps going
defer func() { ... }() defers a call to a function with no name, written right there. After the deferred function runs, safeRun returns normally, and main goes on.
Turning a panic into an error
Most of the time you want the caller to get an error, not a printed message. For that, give the results names, like (v string, err error). Named results are variables that you can set anywhere in the function, and the deferred function can change err before the caller gets it:
package main
import "fmt"
func getAt(s []string, i int) (v string, err error) {
defer func() {
r := recover()
if r != nil {
err = fmt.Errorf("getAt: %v", r)
}
}()
return s[i], nil
}
func main() {
letters := []string{"a", "b", "c"}
fmt.Println(getAt(letters, 1))
_, err := getAt(letters, 7)
fmt.Println(err)
}
Output:
b <nil>
getAt: runtime error: index out of range [7] with length 3
When to use panic
The usual Go advice is simple. Return an error for problems you expect, like bad user input or a missing file. Panic only for bugs, where the code itself is wrong. Do not use panic and recover as a normal way to handle errors. Code that returns errors is easier to read, because every failure is visible at the call.
In the exercise, finish safeDivide so it recovers from a division by zero and returns an error instead.