Sobes.tech
Principal

What happens if you run a goroutine and call panic inside it? Will the goroutine stop or will the entire application stop?

sobes.tech AI

Answer from AI

The question relates to panic behavior in Go goroutines, although the module is specified as C#.

If a panic is called in a goroutine, that specific goroutine will stop, and if the panic is not recovered (for example, using recover), it will terminate with an error. However, if the panic is not caught, it will lead to the termination of the entire application (process), as panic propagates up the call stack and, if not handled, causes the program to exit.

In other words:

  • Panic in a goroutine stops only that goroutine if there is a recover.
  • If recover is absent, panic propagates and terminates the entire application.

Example:

func main() {
    go func() {
        panic("error in goroutine")
    }()
    time.Sleep(time.Second) // to allow the goroutine to execute
}

In this example, the application will terminate with a panic error.