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:
-
In
main, twodeferstatements are declared:- The first with
recover(), which catches a panic and prints "recovered". - The second simply prints "defer".
- The first with
-
A goroutine is started, which prints "inside goroutine start", then calls
panic("boom"), after which the code does not execute. -
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
mainwill be called upon exitingmain. - The goroutine will print "inside goroutine start", then the panic "boom" will cause that goroutine to terminate abruptly, but not the entire program.
recoverinmainwill not catch the panic, as the panic is not inmain.- The deferred
fmt.Println("defer")inmainwill 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.