GoGo
IntermediateLesson 10 of 15

defer, panic & recover – Go

Guarantee cleanup and catch exceptional situations.

defer postpones a function call until the moment the surrounding function ends – no matter how. Multiple defers run in reverse order (LIFO). The arguments, however, are evaluated immediately at the defer statement.

package main

import "fmt"

func main() {
	defer fmt.Println("first defer")
	defer fmt.Println("second defer")
	fmt.Println("Main part")

	for i := 0; i < 3; i++ {
		defer fmt.Println("Loop", i)
	}
	// Output: Hauptteil, Schleife 2, Schleife 1, Schleife 0,
	// second defer, first defer
}

Typical use: schedule closing a resource right after opening it – then you cannot forget it on any return:

package main

import (
	"bufio"
	"fmt"
	"os"
)

func zeilenZaehlen(pfad string) (int, error) {
	f, err := os.Open(pfad)
	if err != nil {
		return 0, err
	}
	defer f.Close() // is guaranteed to run

	sc := bufio.NewScanner(f)
	n := 0
	for sc.Scan() {
		n++
	}
	return n, sc.Err()
}

func main() {
	n, err := zeilenZaehlen("does-not-exist.txt")
	fmt.Println(n, err) // 0 open does-not-exist.txt: no such file or directory
}

panic aborts the normal flow (for programming errors, not for expected errors). recover catches a panic inside a deferred function. Libraries and servers use this so that one failure does not terminate the whole program.

package main

import "fmt"

func sicher(f func()) (err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("panic recovered: %v", r)
		}
	}()
	f()
	return nil
}

func main() {
	fmt.Println(sicher(func() { fmt.Println("all good") })) // all good, then <nil>
	fmt.Println(sicher(func() { panic("broken") }))          // panic recovered: broken
}
WarningTypical panics are out-of-range slice access, writing to a nil map and dereferencing nil pointers. Do not use panic as a replacement for exceptions – for expected errors there is error.