← Вернуться к курсу: Go from scratch

defer, panic, recover and week 3 review

Видео скоро появится

When a function opens a file, a connection or a lock, it must remember to close or release it on every exit path, including those that end in an error. Forgetting one causes resource leaks. Go solves this problem with the word defer, which schedules a call to run right when the function ends, no matter how it ends. In this lesson you will see defer, the exceptional mechanism of panic and recover, and we will close the week with a review of functions and errors.

defer

You write defer in front of a function call. That call is postponed until the function that contains it returns. The arguments are evaluated at the moment of the defer, not when it runs. If there are several defers, they run in reverse order, like a stack: the last one you scheduled is the first to run. The most typical use is placing the release of the resource right below its acquisition, so that both lines stay together and it is hard to forget the second one.

go
package main

import (
	"fmt"
	"os"
)

func readFirstBytes(path string) error {
	f, err := os.Open(path)
	if err != nil {
		return fmt.Errorf("open: %w", err)
	}
	defer f.Close() // always runs when the function returns

	buf := make([]byte, 4)
	n, err := f.Read(buf)
	if err != nil {
		return fmt.Errorf("read: %w", err)
	}
	fmt.Println("read", n, "bytes")
	return nil
}

func main() {
	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred", i) // prints 3, 2, 1 at the end
	}
	fmt.Println("main body")
	if err := readFirstBytes("does-not-exist.txt"); err != nil {
		fmt.Println(err)
	}
}

panic and recover

panic stops the normal flow: the current function ends, its defers run, and the panic climbs up the call stack until the program crashes showing a message and the stack trace. It is produced by programming errors, such as accessing an out-of-range index or using a nil pointer, and you can raise it yourself with panic("message") when the program reaches an impossible state. It is not the normal error mechanism: for expected failures, like a missing file, return an error. With recover, called inside a deferred function, you can intercept the panic and turn it into an error; servers use it so that one faulty request does not bring down the whole process.

go
package main

import "fmt"

func safeIndex(items []int, i int) (value int, err error) {
	defer func() {
		if r := recover(); r != nil {
			err = fmt.Errorf("recovered: %v", r)
		}
	}()
	return items[i], nil // may panic: index out of range
}

func main() {
	v, err := safeIndex([]int{10, 20, 30}, 1)
	fmt.Println(v, err) // 20 <nil>

	v, err = safeIndex([]int{10, 20, 30}, 9)
	fmt.Println(v, err) // 0 recovered: runtime error: index out of range [9] with length 3
}

Week 3 review

This week you learned to write functions with parameters and multiple returns, named results, variadic functions, closures, the error type, wrapping with %w, errors.Is and errors.As, and defer to release resources. These topics are the foundation of every real Go program. In week 4 you will see how to store collections of data with arrays, slices and maps. Solve the exercise and the quiz before moving on.

  • defer runs when leaving the function, in reverse order (LIFO).
  • The arguments of a defer are evaluated when it is declared.
  • panic is for impossible situations; normal failures return an error.
  • recover only works inside a deferred function.

Проверьте себя

Вопрос 1 из 6

What does this print? for i := 1; i <= 3; i++ { defer fmt.Print(i) }

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →