Defer, Panic & Recover - Error Handling Patterns - Go Tutorial #20:
Video: Defer, Panic & Recover - Error Handling Patterns - Go Tutorial #20: by Taught by Celeste AI - AI Coding Coach
Watch full page →Defer, Panic & Recover - Error Handling Patterns in Go
Go provides powerful built-in mechanisms for managing errors and cleanup: defer, panic, and recover. Using defer, you can ensure cleanup code runs even if a function exits early, while panic and recover allow you to handle unexpected errors gracefully.
Code
package main
import (
"fmt"
"os"
)
func main() {
// Defer example: file cleanup guaranteed
file, err := os.Create("example.txt")
if err != nil {
panic(err) // Panic on unrecoverable error
}
// Ensure file is closed when main exits
defer func() {
fmt.Println("Closing file")
file.Close()
}()
fmt.Fprintln(file, "Hello, Go!")
// Demonstrate multiple defers run in LIFO order
defer fmt.Println("First defer")
defer fmt.Println("Second defer")
// Panic and recover example
safeDivide(10, 0)
fmt.Println("Program continues after recover")
}
func safeDivide(a, b int) {
// Recover from panic inside deferred function
defer func() {
if r := recover(); r != nil {
fmt.Println("Recovered from panic:", r)
}
}()
if b == 0 {
panic("division by zero")
}
fmt.Println("Result:", a/b)
}
Key Points
deferschedules a function to run after the surrounding function returns, useful for cleanup.- Multiple deferred calls execute in last-in, first-out (LIFO) order.
panicstops normal execution and begins unwinding the stack, signaling a serious error.recovercan regain control from a panic inside a deferred function, allowing graceful error handling.- Combining these patterns helps write robust Go programs that clean up resources and handle unexpected failures.