Home >Backend Development >Golang >Can a Caller Function Recover from Panics in Child Goroutines in Go?
Recovery from Child Goroutine Panics in Go
During a recent programming endeavor, a fundamental assumption was challenged: the ability of a caller function to recover from the panics of child goroutines. Despite conventional wisdom suggesting otherwise, it was discovered that a caller's deferred recovery mechanism fails to prevent the termination of the entire program when a child goroutine falls victim to panic.
To illustrate this puzzling behavior, consider the following code:
<code class="go">func fun1() { fmt.Println("fun1 started") defer func() { if err := recover(); err != nil { fmt.Println("recover in func1") } }() go fun2() time.Sleep(10 * time.Second) // wait for the boom! fmt.Println("fun1 ended") } func fun2() { fmt.Println("fun2 started") time.Sleep(5 * time.Second) panic("fun2 booom!") fmt.Println("fun2 ended") }</code>
Intriguingly, regardless of whether fun1 concludes before or after fun2's panic, the deferred recover mechanism in fun1 proves ineffective, leading to the program's immediate demise.
Reasoning behind the Failure
The Go specification provides clarity on this unconventional behavior:
While executing a function F, an explicit call to panic or a run-time panic terminates the execution of F. Any functions deferred by F are then executed as usual. Next, any deferred functions run by F's caller are run, and so on up to any deferred by the top-level function in the executing goroutine. At that point, the program is terminated and the error condition is reported, including the value of the argument to panic.
In this case, fun2 represents the top-level function executing in its respective goroutine. As fun2 lacks a recovery mechanism, the program terminates upon its panic, disregarding any deferred recovery attempts in fun1 or its predecessors.
This behavior underscores a crucial distinction: a goroutine cannot recover from a panic originating in a separate goroutine. Consequently, the deferred recover in fun1 becomes futile, as the panic in fun2 effectively terminates the goroutine and any subsequent recovery efforts.
The above is the detailed content of Can a Caller Function Recover from Panics in Child Goroutines in Go?. For more information, please follow other related articles on the PHP Chinese website!