Junior — Middle
Is it possible to handle panic inside a child goroutine so that it affects the parent goroutine?
sobes.tech AI
Answer from AI
In Go, a panic inside a child goroutine does not directly affect the parent goroutine, as each goroutine operates independently. You can handle a panic inside a child goroutine using recover(), but this is local — it does not automatically pass the error to the parent.
If you want the parent to be aware of a panic in the child goroutine, the usual approach is:
- Use
deferwithrecover()inside the child goroutine to catch the panic. - After catching the panic, send the error information through a channel to the parent.
- The parent goroutine reads from the channel and decides, for example, to terminate or handle the error.
Example:
func child(ch chan<- error) {
defer func() {
if r := recover(); r != nil {
ch <- fmt.Errorf("panic: %v", r)
}
}()
// code that may cause a panic
panic("something went wrong")
}
func parent() {
ch := make(chan error)
go child(ch)
err := <-ch
if err != nil {
fmt.Println("Child goroutine panicked:", err)
// handle error
}
}
Thus, the panic is handled within the child goroutine, and the parent receives a notification and can react.