DEV Community

Jie
Jie

Posted on • Originally published at jma.im

Panic/recover and goroutine in Golang

The panic recover is only alive within the current thread, that means each goroutine need it’s own panic recover

The panic in this goroutine, wont be caught by the recover, it will panic.

defer func() {
    if rec := recover(); rec != nil {
        fmt.Println("Catched panic", rec)
    }
}()
fmt.Println("Hello, playground")
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
    defer wg.Done()
    panic("You can't catch me!")
}()
wg.Wait()
Enter fullscreen mode Exit fullscreen mode

To catch the panic inside of the goroutine, you need code the recover again

defer func() {
    if rec := recover(); rec != nil {
        fmt.Println("Catched panic", rec)
    }
}()
fmt.Println("Hello, playground")
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
    defer func() {
        if rec := recover(); rec != nil {
            fmt.Printf("Now catched `%v`\n", rec)
        }
    }()
    defer wg.Done()
    panic("You can't catch me!")
}()
wg.Wait()
Enter fullscreen mode Exit fullscreen mode

More reading

Website: jma.dev
Weekly tech bookmarks: funcmarks

Top comments (0)