π 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")
}
Output
Program started
Recovered from panic: Something went wrong!
π¨ 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)