Golang / GoLang Basics Interview Questions
How do defer, panic, and recover work together in Go?
defer schedules a function call to run when the surrounding function returns — regardless of how it returns (normally, via error, or via panic). It is Go's idiomatic resource-cleanup mechanism. panic stops normal execution; recover catches it inside a deferred function.
// defer â executes when surrounding function returns func processFile(path string) error { f, err := os.Open(path) if err != nil { return err } defer f.Close() // ALWAYS runs, even if function returns early // process file... return nil } // Multiple defers: LIFO order (last-in, first-out) func demo() { defer fmt.Println("3rd") // runs first (LIFO) defer fmt.Println("2nd") defer fmt.Println("1st") // runs last? NO â runs first! // Output order: 1st, 2nd, 3rd â wait, no: // ACTUAL order: 3rd â 2nd â 1st (LIFO!) } // Defer argument evaluation: immediate, not deferred! x := 5 defer fmt.Println(x) // prints 5 â x evaluated NOW x = 10 // too late to affect the defer // panic â signals an unrecoverable error func mustPositive(n int) int { if n <= 0 { panic(fmt.Sprintf("expected positive, got %d", n)) } return n } // recover â catches a panic; ONLY useful inside defer func safeDiv(a, b int) (result int, err error) { defer func() { if r := recover(); r != nil { err = fmt.Errorf("recovered: %v", r) } }() return a / b, nil // panics if b == 0 }
More Related questions...