Consider the following Go code that uses recover() inside a deferred function. What will it print?
package main import "fmt" func main() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered from panic:", r) } }() fmt.Println("Start") panic("something went wrong") fmt.Println("End") }
Remember that defer runs after the panic, and recover() stops the panic.
The program prints "Start" first. Then it panics. The deferred function runs and calls recover(), which catches the panic and prints the message. The line after panic is never reached.
What will this Go program print?
package main import "fmt" func main() { r := recover() fmt.Println("Recover returned:", r) panic("panic here") }
recover() only works inside deferred functions during a panic.
Since recover() is called outside a deferred function and no panic is active, it returns nil. Then the program panics and prints the panic message.
Look at this Go code. It tries to recover from a panic but fails. Why?
package main import "fmt" func main() { defer recoverPanic() panic("fail") } func recoverPanic() { if r := recover(); r != nil { fmt.Println("Recovered:", r) } }
Think about where the panic happens and where recover is called.
Recover only catches panics if called directly in the deferred function where the panic happened. Here, recover is called in a separate function deferred by main, so it cannot catch the panic from main.
Which of the following Go code snippets correctly uses recover() to handle a panic?
Recover must be called inside a deferred function to catch panics.
Option B correctly defines an anonymous deferred function that calls recover and checks if a panic occurred. Option B calls recover directly in defer, which does nothing. Option B calls recover in a normal function deferred, but recover only works if called directly in the deferred function. Option B calls recover but ignores the result, so it does not handle the panic.
Consider this Go program with nested panics and deferred recover calls. How many times will the recover print a message?
package main import "fmt" func main() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in main:", r) } }() func() { defer func() { if r := recover(); r != nil { fmt.Println("Recovered in inner func:", r) panic("new panic") } }() panic("original panic") }() }
Think about how recover stops a panic and how a new panic inside a deferred function affects outer deferred functions.
The inner deferred function recovers from the original panic and prints a message. Then it panics again with a new panic. The outer deferred function in main recovers from this new panic and prints its message. So recover prints twice.