Complete the code to recover from a panic and print a message.
func safeDivide(a, b int) {
defer func() {
if r := [1](); r != nil {
println("Recovered from panic:", r)
}
}()
println(a / b)
}The recover() function is used inside a deferred function to catch a panic and prevent the program from crashing.
Complete the code to safely handle a panic and print a custom message.
func handlePanic() {
defer func() {
if err := [1](); err != nil {
println("Error caught:", err)
}
}()
panic("something went wrong")
}recover() captures the panic value inside the deferred function, allowing graceful error handling.
Fix the error in the code to properly recover from a panic.
func faulty() {
defer func() {
if r := [1](); r != nil {
println("Recovered:", r)
}
}()
panic("fail")
}The recover() function must be called with parentheses to execute it and get the panic value.
Fill both blanks to create a function that recovers from panic and prints the panic message.
func safeRun() {
defer func() {
if err := [1](); err != nil {
println("Caught panic:", [2])
}
}()
panic("unexpected error")
}Use recover() to get the panic value and print the variable holding it.
Fill all three blanks to recover from panic and print a detailed message.
func execute() {
defer func() {
if panicVal := [1](); panicVal != nil {
println("Recovered panic:", [2], "with value", [3])
}
}()
panic("critical failure")
}Call recover() to get the panic value, then print the variable holding it twice for clarity.