Home > Backend Development > Golang > How to Handle Panics in Separate Go Routines?

How to Handle Panics in Separate Go Routines?

DDD
Release: 2024-11-07 20:36:02
Original
459 people have browsed it

How to Handle Panics in Separate Go Routines?

Handling Panics in Go Routines

When a panic occurs in a Go routine, it is essential to handle it properly. Using the recover function can effectively retrieve the panic value and handle it accordingly.

One common approach is to handle panics in the main function using deferred functions. However, when the panic occurs in a separate goroutine, this approach fails to capture it.

In the example given:

func main() {
    done := make(chan int64)
    defer fmt.Println("Graceful End of program")
    defer func() {
        r := recover()
        if _, ok := r.(error); ok {
            fmt.Println("Recovered")
        }
    }()

    go handle(done)
    for {
        select {
        case <-done:
            return
        }
    }
}

func handle(done chan int64) {
    var a *int64
    a = nil

    fmt.Println(*a)
    done <- *a
}
Copy after login

The panic occurs in the handle function within the goroutine, but the deferred recover function in the main function cannot capture it. This is because recover only works when invoked in the same goroutine where the panic originated.

To resolve this issue, move the deferred recover function call within the handle function:

func main() {
    done := make(chan int64)
    defer fmt.Println("Graceful End of program")

    go handle(done)
    for {
        select {
        case <-done:
            return
        }
    }
}

func handle(done chan int64) {
    defer func() {
        r := recover()
        if _, ok := r.(error); ok {
            fmt.Println("Recovered")
        }
    }()

    var a *int64
    a = nil

    fmt.Println(*a)
    done <- *a
}
Copy after login

With this modification, when a panic arises in the handle function, the deferred recover function within the same goroutine will catch and process it accordingly.

The above is the detailed content of How to Handle Panics in Separate Go Routines?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template