Middle
What happens if you start a goroutine and call panic within it? Will the goroutine stop or will the entire application stop?
sobes.tech AI
Answer from AI
If a panic occurs in a goroutine, that specific goroutine will stop, but the entire application will not automatically terminate. A panic in a goroutine does not lead to stopping all goroutines or the program unless it reaches the top level and remains unhandled.
To prevent the application from crashing, you can use recover inside the same goroutine or in the calling function to catch and handle the panic.
Example:
go func() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Panic recovered in goroutine:", r)
}
}()
panic("something went wrong")
}()
In this example, the panic will not cause the entire application to stop, but will be handled inside the goroutine.