DEV Community

Cover image for Handling Panic in Go with recover() ⚡
Dzung Nguyen
Dzung Nguyen

Posted on

Handling Panic in Go with recover() ⚡

👉 In Go, a panic can occur due to unexpected runtime errors. When this happens, the program immediately stops execution.

👉 Go provides a built-in function, recover(), that allows you to gracefully handle panics and ensure cleanup tasks are properly executed. 🛠️

Sample Code

package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()

    fmt.Println("Program started")
    panic("Something went wrong!")
    fmt.Println("This will not be executed")
}
Enter fullscreen mode Exit fullscreen mode

Output

Program started  
Recovered from panic: Something went wrong!
Enter fullscreen mode Exit fullscreen mode

🚨 Important Notes

recover() only works inside a deferred function

✅ If recover() is not called, the program will crash

✅ Use recover() for exceptional, unexpected situations or critical cleanup and at the highest level possible (like worker process/ main function)

✅ Abuse recover() can hide real bugs and make debugging harder! ⚠️⚠️


Follow me to stay updated with my future posts:

Top comments (0)