Sobes.tech
Senior

The code snippet provided is a Go program with deferred functions and a goroutine that panics. What will be the output?

sobes.tech AI

Answer from AI

This code has several important points related to the behavior of defer, recover, and goroutines:

  1. In main, two defer statements are declared:

    • The first with recover(), which catches a panic and prints "recovered".
    • The second simply prints "defer".
  2. A goroutine is started, which prints "inside goroutine start", then calls panic("boom"), after which the code does not execute.

  3. time.Sleep(time.Second) gives the goroutine time to execute.

Key point: recover() only works if the panic occurs in the same goroutine where the defer with recover is called. In this case, the panic occurs in a separate goroutine, and recover is in main.

What will happen when running:

  • The deferred functions in main will be called upon exiting main.
  • The goroutine will print "inside goroutine start", then the panic "boom" will cause that goroutine to terminate abruptly, but not the entire program.
  • recover in main will not catch the panic, as the panic is not in main.
  • The deferred fmt.Println("defer") in main will execute.

Console output:

inside goroutine start
defer

The panic in the goroutine will not be caught, and the message "recovered" will not be printed.

If you want to handle a panic in a goroutine, recover must be inside the same goroutine:

go func() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered in goroutine")
        }
    }()
    fmt.Println("inside goroutine start")
    panic("boom")
}()

Then, the panic will be caught, and the program will not crash.

The code snippet provided is a Go program with… - sobes.tech