Home  >  Article  >  Backend Development  >  Can a Caller Function Recover from a Child Goroutine\'s Panic in Go?

Can a Caller Function Recover from a Child Goroutine\'s Panic in Go?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 18:10:02930browse

Can a Caller Function Recover from a Child Goroutine's Panic in Go?

How Does a Caller Function Recover from Child Goroutine's Panics?

Previously, it was assumed that a panic in a goroutine would terminate the program if its caller completed before the panic occurred. However, experimenting with a sample code revealed otherwise.

Sample 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>

Unexpected Behavior:

Despite the expectation that the caller function's recovery mechanism would handle the goroutine's panic, the entire program still terminated.

Explanation:

The Go specification states that:

When fun2 is the top-level function executing in the goroutine and fun2 does not recover from a panic, the program terminates when fun2 panics.

Since fun2 is the top-level function in its goroutine and it does not handle the panic, the program terminates prematurely.

Goroutine Autonomy:

A goroutine cannot recover from a panic in another goroutine. Therefore, the deferred call in fun1 is not invoked when fun2 panics.

Conclusion:

A caller function cannot recover from panics in goroutines it creates unless the goroutine explicitly recovers from the panic before the program caller terminates.

The above is the detailed content of Can a Caller Function Recover from a Child Goroutine\'s Panic in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn