Complete the code to cause a panic with the message "error occurred".
func main() {
panic([1])
}The panic function takes a value to display as the panic message. It must be a string literal here.
Complete the code to recover from a panic inside the deferred function.
func main() {
defer func() {
if r := [1](); r != nil {
println("Recovered from panic")
}
}()
panic("fail")
}The recover function is used inside a deferred function to catch a panic and prevent the program from crashing.
Fix the error in the code to properly recover from a panic and print the panic message.
func main() {
defer func() {
if r := [1](); r != nil {
println("Panic message:", r)
}
}()
panic("something went wrong")
}Using recover() inside a deferred function allows catching the panic and accessing its message.
Fill both blanks to create a map of strings to their lengths, but only include words longer than 3 characters.
func main() {
words := []string{"go", "code", "panic", "fun"}
lengths := map[string]int{
[1]: len([2]) for _, word := range words if len(word) > 3
}
fmt.Println(lengths)
}We use word as the key and len(word) as the value for each word longer than 3 characters.
Note: Go does not support map comprehensions like this; this is a conceptual exercise.
Fill all three blanks to create a deferred function that recovers from panic and prints the panic message.
func main() {
defer func() {
if r := [1](); r != nil {
fmt.[2]("Recovered panic: %v", [3])
}
}()
panic("unexpected error")
}Use recover() to catch the panic, fmt.Printf to print formatted output, and r as the recovered panic message.