0
0
Goprogramming~10 mins

Panic behavior in Go - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to cause a panic with the message "error occurred".

Go
func main() {
    panic([1])
}
Drag options to blanks, or click blank then click option'
A"error occurred"
Berror occurred
Cpanic("error occurred")
Dfmt.Println("error occurred")
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting quotes around the string message
Calling panic inside panic argument
Using print functions instead of panic
2fill in blank
medium

Complete the code to recover from a panic inside the deferred function.

Go
func main() {
    defer func() {
        if r := [1](); r != nil {
            println("Recovered from panic")
        }
    }()
    panic("fail")
}
Drag options to blanks, or click blank then click option'
Arecover
Bclose
Cdefer
Dpanic
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic instead of recover
Calling recover outside a deferred function
Not checking if recover returned nil
3fill in blank
hard

Fix the error in the code to properly recover from a panic and print the panic message.

Go
func main() {
    defer func() {
        if r := [1](); r != nil {
            println("Panic message:", r)
        }
    }()
    panic("something went wrong")
}
Drag options to blanks, or click blank then click option'
Afmt.Println
Brecover
Cpanic
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic instead of recover
Trying to recover outside defer
Not checking if recover returned nil
4fill in blank
hard

Fill both blanks to create a map of strings to their lengths, but only include words longer than 3 characters.

Go
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)
}
Drag options to blanks, or click blank then click option'
Aword
Bwords
Clen(word)
Dword.len
Attempts:
3 left
💡 Hint
Common Mistakes
Using the whole slice as key or value
Trying to call len as a method
Using wrong variable names
5fill in blank
hard

Fill all three blanks to create a deferred function that recovers from panic and prints the panic message.

Go
func main() {
    defer func() {
        if r := [1](); r != nil {
            fmt.[2]("Recovered panic: %v", [3])
        }
    }()
    panic("unexpected error")
}
Drag options to blanks, or click blank then click option'
Apanic
Brecover
Cr
DPrintf
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic instead of recover
Using fmt.Println instead of fmt.Printf
Not passing the recovered value to print