This flow shows how defer and recover work together to catch and handle panics inside a function.
Execution Sample
Go
func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
return a / b
}
This function divides two numbers but recovers from a panic if division by zero happens.
Execution Table
Step
Action
Evaluation
Result
1
Call safeDivide(10, 2)
No panic
Returns 5
2
Call safeDivide(10, 0)
Panic: division by zero
recover() catches panic
3
Deferred function runs
recover() returns panic info
Prints 'Recovered from panic: runtime error: integer divide by zero'
4
safeDivide returns
No value returned explicitly after panic
Returns 0 (default int)
5
Program continues
No crash
Execution continues normally
💡 Execution stops normally after recover handles panic, preventing program crash.
Variable Tracker
Variable
Start
After Step 1
After Step 2
After Step 3
Final
a
10
10
10
10
10
b
2 or 0
2 or 0
2 or 0
2 or 0
2 or 0
r (recover)
nil
nil
panic info or nil
panic info or nil
nil after defer ends
Key Moments - 3 Insights
Why does the program not crash when dividing by zero inside safeDivide?
Because the deferred function calls recover(), which catches the panic and prevents the program from crashing, as shown in execution_table step 3.
What does recover() return if there is no panic?
recover() returns nil if no panic occurred, so the deferred function does nothing, as seen in execution_table step 1.
Why does safeDivide return 0 after a panic?
After a panic, the function does not reach the return statement normally, so it returns the zero value for int, which is 0, as shown in execution_table step 4.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what does recover() return at step 3 when a panic occurs?
Anil
BThe result of division
CThe panic information (error message)
DA boolean true
💡 Hint
Check execution_table row 3 under 'Evaluation' and 'Result' columns.
At which step does the program print the recovered panic message?
AStep 1
BStep 3
CStep 2
DStep 5
💡 Hint
Look at execution_table row 3 under 'Result' for the print statement.
If recover() was not used, what would happen at step 2?
APanic would crash the program
BProgram would continue normally
CFunction would return 0
DPanic would be ignored
💡 Hint
Refer to the concept_flow and execution_table exit_note about panic handling.
Concept Snapshot
func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
// handle panic
}
}()
return a / b
}
- Use defer + recover to catch panics
- recover returns panic info or nil
- Prevents program crash on runtime errors
Full Transcript
This example shows how Go's recover function works inside a deferred function to catch panics. When safeDivide is called with b=0, a panic occurs due to division by zero. The deferred anonymous function calls recover(), which returns the panic information. This stops the panic from crashing the program. The function then returns the zero value for int, which is 0. If no panic occurs, recover returns nil and the function returns the division result normally. This technique helps keep programs running safely even when unexpected errors happen.
Practice
(1/5)
1. What is the main purpose of the recover function in Go?
easy
A. To handle errors returned by functions
B. To start a new goroutine
C. To pause the execution of a function
D. To catch a panic and prevent the program from crashing
Solution
Step 1: Understand panic and recover
Panic causes a program to stop immediately unless recovered.
Step 2: Role of recover
Recover catches the panic inside a deferred function to keep the program running.
Final Answer:
To catch a panic and prevent the program from crashing -> Option D
Quick Check:
recover catches panic = A [OK]
Hint: Recover catches panics only inside deferred functions [OK]
Common Mistakes:
Thinking recover handles normal errors
Using recover outside deferred functions
Confusing recover with panic
2. Which of the following is the correct way to use recover in Go?
easy
A. Call recover directly inside the main function
B. Call recover inside a deferred function
C. Call recover inside a goroutine
D. Call recover after a panic has finished
Solution
Step 1: Identify recover usage rules
Recover must be called inside a deferred function to catch panics.
Step 2: Analyze options
Only Call recover inside a deferred function calls recover inside a deferred function.
Final Answer:
Call recover inside a deferred function -> Option B
Quick Check:
recover inside defer = B [OK]
Hint: Always use recover inside defer to catch panics safely [OK]
Common Mistakes:
Calling recover directly without defer
Calling recover after panic ends
Using recover in goroutines without defer
3. What will be the output of this Go program?
package main
import "fmt"
func main() {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
panic("something went wrong")
fmt.Println("This will not print")
}
medium
A. Recovered from panic: something went wrong
B. something went wrong
C. This will not print
D. Program crashes with panic message
Solution
Step 1: Understand defer and recover behavior
The deferred function runs after panic starts, calling recover to catch it.
Step 2: Output analysis
Recover prints the panic message, so output is "Recovered from panic: something went wrong".
Final Answer:
Recovered from panic: something went wrong -> Option A
Quick Check:
defer + recover prints panic message = C [OK]
Hint: Recover prints panic message inside deferred function [OK]
Common Mistakes:
Expecting code after panic to run
Thinking panic message prints directly
Ignoring deferred recover function
4. What is wrong with this Go code snippet?
func main() {
recover()
panic("error")
}
medium
A. panic() cannot be called without defer
B. panic() must be called before recover()
C. recover() is called outside a deferred function and will not catch panic
D. recover() cannot be called in main function
Solution
Step 1: Check recover usage
Recover only works inside deferred functions to catch panics.
Step 2: Analyze code
Recover is called directly, so it won't catch the panic, causing program to crash.
Final Answer:
recover() is called outside a deferred function and will not catch panic -> Option C
Quick Check:
recover outside defer = no panic catch = D [OK]
Hint: Recover must be inside defer to catch panic [OK]
Common Mistakes:
Calling recover directly without defer
Assuming recover catches panic anytime
Misunderstanding panic and recover order
5. You want to safely handle panics in a function that divides two numbers and returns the result. Which code snippet correctly uses recover to avoid crashing when dividing by zero?
hard
A. func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic")
}
}()
return a / b
}
B. func safeDivide(a, b int) int {
if b == 0 {
recover()
}
return a / b
}
C. func safeDivide(a, b int) int {
return a / b
defer recover()
}
D. func safeDivide(a, b int) int {
defer recover()
return a / b
}
Solution
Step 1: Identify correct recover usage
Recover must be called inside a deferred anonymous function to catch panics.
Step 2: Analyze options
Only func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic")
}
}()
return a / b
} uses defer with an anonymous function calling recover properly.
Final Answer:
func safeDivide(a, b int) int {
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic")
}
}()
return a / b
} -> Option A
Quick Check:
defer func with recover = safe panic handling = A [OK]
Hint: Use defer with anonymous func calling recover to catch panics [OK]
Common Mistakes:
Calling recover without defer
Calling recover outside anonymous function
Placing defer after return statement
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.