Defer, Panic & RecoverBeginner
1Question 1 of 1
goHow do defer, panic, and recover manage control flow and cleanup in Go?
Explanation & Concept
• `defer`: Defers execution of a function until the surrounding function returns. Evaluated in LIFO (last-in, first-out) order. Essential for releasing mutexes and closing files. • `panic`: Halts normal execution, runs deferred functions, and crashes the program with a stack trace. • `recover`: Built-in function that regains control of a panicking goroutine when called inside a deferred function.
Code Example
go
package main
import "fmt"
func safeExecute() {
defer func() {
if r := recover(); r != nil {
fmt.Printf("Recovered from panic: %v\n", r)
}
}()
fmt.Println("Executing task...")
panic("Catastrophic runtime failure!")
}
func main() {
safeExecute()
fmt.Println("Program recovered and continuing normally.")
}How It Works & Key Takeaways
`defer` ensures cleanup routines execute reliably even when unexpected panics interrupt function execution.
Mock Test · 1 Questions · Optional
Ready for Concurrency Patterns?
Take a quick test to evaluate yourself, or move straight to the next module.
Intermediate1 questions