0
0
Goprogramming~5 mins

Recover usage in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the recover function in Go?

recover is used to regain control of a panicking goroutine. It allows a program to handle a panic and continue running instead of crashing.

Click to reveal answer
beginner
Where must recover be called to successfully catch a panic?

recover must be called inside a deferred function. If called outside a deferred function, it will not stop the panic.

Click to reveal answer
beginner
What happens if recover is called and there is no panic?

If recover is called when there is no panic, it returns nil and does nothing else.

Click to reveal answer
intermediate
Explain the relationship between panic, defer, and recover in Go.

panic stops normal execution and starts panicking. defer functions run even during panic. Inside a deferred function, recover can catch the panic and stop the program from crashing.

Click to reveal answer
beginner
Show a simple Go code snippet that uses recover to handle a panic.
func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    return a / b
}
Click to reveal answer
What does recover return when called during a panic?
ABoolean true
BThe value passed to panic
CAn error object
DAlways nil
Where should recover be placed to catch a panic?
AInside a deferred function
BAnywhere in the code
CInside the main function only
DInside a goroutine only
What happens if a panic is not recovered?
AProgram crashes and prints stack trace
BProgram continues normally
CProgram silently ignores panic
DProgram restarts automatically
Which keyword is used to delay execution of a function until the surrounding function returns?
Arecover
Bpanic
Cdefer
Dgo
Can recover stop a panic if called outside a deferred function?
AYes, always
BOnly if panic is recent
COnly inside main function
DNo, it returns nil and does nothing
Describe how to use recover to handle a panic in Go.
Think about how defer and recover work together.
You got /4 concepts.
    Explain the flow of a Go program when a panic occurs and is recovered.
    Focus on panic, defer, and recover sequence.
    You got /4 concepts.