Go panic
Internal
Overview
Use panics in truly exceptional cases.
A panic indicates a programmer error (attempting to access an array index out of bounds, writing an uninitialized map, etc.). Panics can also be triggered with:
panic(<message>)
The panic can be caught on the stack outside the function that caused the panic, by executing recover()
. Recover can be called in any upper function on the stack, or even if the function that triggers the panic, if the invocation is made with defer
.
The recover()
built-in function allows a program to manage behavior of a panicking goroutine. Executing a call to recover inside a deferred function, but not any function called by it, stops the panicking sequence by restoring normal execution and retrieves the error value passed to the call of panic. If recover is called outside the deferred function it will not stop a panicking sequence. In this case, or when the goroutine is not panicking, or if the argument supplied to panic was nil
, recover returns nil
. Thus the return value from recover reports whether the goroutine is panicking.