Senior
What happens if you start a goroutine and call panic within it?
sobes.tech AI
Answer from AI
If a panic is called in a goroutine, this panic will be local to that goroutine and will lead to its abrupt termination if not handled (recover).
Important:
- A panic in one goroutine will not stop other goroutines or terminate the entire program unless it occurs in the main goroutine.
- To prevent the entire program from crashing, use
deferwithrecoverinside the goroutine to catch the panic.
Example:
go func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Panic caught in goroutine:", r)
}
}()
panic("something went wrong")
}()
Without recover, the panic will terminate this goroutine, but others will continue to run.