Recover from a panic

yourbasic.org/golang

The built-in recover function can be used to regain control of a panicking goroutine and resume normal execution.

Because the only code that runs while unwinding is inside deferred functions, recover is only useful inside deferred functions.

Example

func main() {
	n := foo()
	fmt.Println("main received", n)
}

func foo() int {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
		}
	}()
	m := 1
	panic("foo: fail")
	m = 2
	return m
}
foo: fail
main received 0

Since the panic occured before foo returned a value, n still has its initial zero value.

Return a value

To return a value during a panic, you must use a named return value.

func main() {
	n := foo()
	fmt.Println("main received", n)
}

func foo() (m int) {
	defer func() {
		if err := recover(); err != nil {
			fmt.Println(err)
			m = 2
		}
	}()
	m = 1
	panic("foo: fail")
	m = 3
	return m
}
foo: fail
main received 2

Share this page: