Go: Panic explained

A program panics by calling the built-in panic function. When it panics, the remaining part of the function is skipped.

statement statement statement panic("Argh!") statement statement statement

Before the function returns, it runs any deferred functions.

func foo() { defer bar() statement panic("Argh!") statement statement } func bar() { statement statement statement statement statement } Return panicking

The stack then unwinds. From the callers perspective it’s just as if it had called panic itself. In the example below, baz calls qux, which then panics:

func baz() { statement statement qux() Return panicking statement statement } func qux() { statement statement panic("Argh!") Return panicking statement statement }

The call stack keeps unwinding until the program crashes, or until it recovers from the panic. (The semantics is similar to how exceptions work in Java and C++.)

Recovering from a panic

A program recovers from a panic by calling the built-in function recover, after which normal execution is resumed. Since all the functions ordinary code is skipped during a panic, the only chance you have to call recover is from within a deferred function.

func foo() { defer bar() statement panic("Argh!") statement statement } func bar() { statement statement recover() statement statement } Return normally

The recover function returns whatever you gave as argument to the panic function. (During normal operation it will return nil.)

When to panic?

A function should only panic if it can not handle the situation and it’s unlikely that the caller will be able to continue execution. For other types of errors it’s idiomatic to use error-indicating return values.

Comments