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)