Go: Panic explained
A program panics by calling the built-in panic
function. When it panics, the remaining part of the function is skipped.
Before the function returns, it runs any deferred functions.
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:
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.
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.