Middle
What happens if a panic occurs in a goroutine without defer-recover?
sobes.tech AI
Answer from AI
If a panic occurs in a goroutine, and there is no deferred recover function in that goroutine, the panic propagates up the call stack of that goroutine and causes only that goroutine to terminate. Other goroutines continue to run.
However, if the panic is not recovered in the main goroutine, it will cause the entire program to terminate with a stack trace.
Example:
func main() {
go func() {
panic("error in goroutine")
}()
time.Sleep(time.Second) // to allow the goroutine to run
fmt.Println("program continues")
}
In this example, a panic in the goroutine will not stop the program because it is not in the main goroutine and is not recovered. If a panic occurs in the main goroutine without recover, the program will terminate with an error.