Go: How Does a Program Recover?
Panics in Go are triggered when the program cannot handle an error properly, such as invalid memory access. It can also be triggered by the developer if the error is unexpected and there is no other way to deal with it. Understanding the process of recovery or termination can be useful to understand the consequences of a panicking program.
Multiple Frames
The classic example for a panic and its recover function is well documented, including by the Go blog in “Defer, Panic, and Recover.” Let’s focus on a different example where a panic involves multiple frames of deferred functions. Here is an example:
This program is composed of three functions that are called in chains. Once the code reaches the panic in the last level, Go will build the first frame of deferred functions and run it:
The code run in that frame did not recover the panic. Then, Go builds the parent frame and calls each deferred function in that frame: