Sobes.tech
Senior

```go func fail() { panic("Fail!") } func main() { fmt.Println("Start!") var wg sync.WaitGroup wg.Add(1) go func() { defer func() { if e := recover(); e != nil { fmt.Println(e) } }() fail() wg.Done() }() wg.Wait() fmt.Println("Finish!") } ```

sobes.tech AI

Answer from AI

In this code, there is an error in the order of calling wg.Done(). In the goroutine, wg.Done() is called after fail(), which causes a panic. Because of this, wg.Done() is never executed, and wg.Wait() in main will block forever.

To fix this, you should call wg.Done() in a defer statement to ensure it runs even if a panic occurs:

var wg sync.WaitGroup
wg.Add(1)
go func() {
    defer wg.Done() // ensure it's called
    defer func() {
        if e := recover(); e != nil {
            fmt.Println(e)
        }
    }()

    fail() // will cause panic
}()
wg.Wait()

This way, wg.Done() will be called, wg.Wait() will unblock, and the program will terminate correctly, printing "Fail!" and "Finish!". In the original version, the program would hang on wg.Wait().

```go func fail() { panic("Fail!") } func main() {… - sobes.tech