Junior — Senior
Catching panic that occurs in a goroutine in the main function
livecode
Task condition
It needs to be determined whether the panic that occurs in the printNumber function is caught by the recover() block in the main function.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println(r)
}
}()
var wg sync.WaitGroup
sem := make(chan struct{}, 5)
for idx := 0; idx < 10; idx++ {
wg.Add(1)
go func(num int) {
defer wg.Done()
printNumber(sem, num)
}(idx)
}
wg.Wait()
close(sem)
}
func printNumber(sem chan struct{}, n int) {
sem <- struct{}{}
time.Sleep(time.Second)
fmt.Println(1 / n)
<-sem
}