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()

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()

More reading

Website: jma.dev
Weekly tech bookmarks: funcmarks

Possibly Related Posts