0
0
Goprogramming~10 mins

Recover usage 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 recover from a panic and print a message.

Go
func safeDivide(a, b int) {
    defer func() {
        if r := [1](); r != nil {
            println("Recovered from panic:", r)
        }
    }()
    println(a / b)
}
Drag options to blanks, or click blank then click option'
Arecover
Bpanic
Cdefer
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic() instead of recover() inside the deferred function.
Calling recover() outside a deferred function.
2fill in blank
medium

Complete the code to safely handle a panic and print a custom message.

Go
func handlePanic() {
    defer func() {
        if err := [1](); err != nil {
            println("Error caught:", err)
        }
    }()
    panic("something went wrong")
}
Drag options to blanks, or click blank then click option'
Arecover
Bpanic
Cclose
Dexit
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic() instead of recover() to catch errors.
Not using defer with recover().
3fill in blank
hard

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

Go
func faulty() {
    defer func() {
        if r := [1](); r != nil {
            println("Recovered:", r)
        }
    }()
    panic("fail")
}
Drag options to blanks, or click blank then click option'
Apanic()
Brecover
Crecover()
Ddefer
Attempts:
3 left
💡 Hint
Common Mistakes
Using recover without parentheses.
Calling panic instead of recover.
4fill in blank
hard

Fill both blanks to create a function that recovers from panic and prints the panic message.

Go
func safeRun() {
    defer func() {
        if err := [1](); err != nil {
            println("Caught panic:", [2])
        }
    }()
    panic("unexpected error")
}
Drag options to blanks, or click blank then click option'
Arecover
Berr
Cpanic
Drecover()
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic instead of recover.
Printing recover() instead of the variable.
5fill in blank
hard

Fill all three blanks to recover from panic and print a detailed message.

Go
func execute() {
    defer func() {
        if panicVal := [1](); panicVal != nil {
            println("Recovered panic:", [2], "with value", [3])
        }
    }()
    panic("critical failure")
}
Drag options to blanks, or click blank then click option'
Arecover
BpanicVal
Dpanic
Attempts:
3 left
💡 Hint
Common Mistakes
Using panic instead of recover.
Using different variable names inconsistently.