Essential Go Panic and recover  Edit on GitHub      File Issue


A panic halts normal execution flow and exits the current function.

Any deferred calls will then be executed before control is passed to the next function higher on the stack.

Each stack’s function will exit and run deferred calls until the panic is handled using a deferred recover(), or until the panic reaches main() and terminates the program.

If this occurs, the argument provided to panic and a stack trace will be printed to stderr.

func foo() {
	defer fmt.Println("Exiting foo")

func main() {
	defer fmt.Println("Exiting main")
Exiting foo
Exiting main
panic: bar

goroutine 1 [running]:
	/books/go/0200-panic-and-recover/panic.go:8 +0x95
	/books/go/0200-panic-and-recover/panic.go:13 +0x7e
exit status 2

panic accepts any type as its parameter.

  ↑ ↓ to navigate     ↵ to select     Esc to close