How do I recover from panics safely in Go?

In Go, panics can occur during unexpected situations, and it's crucial to handle them elegantly to prevent your program from crashing. You can recover from panics in Go using the `defer` statement along with the built-in `recover` function. This allows your application to regain control and continue execution even after a panic event occurs.

Example of Recovering from Panics


package main

import (
    "fmt"
)

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

    fmt.Println("Before panic")
    panic("Something went wrong!")
    fmt.Println("This line will not be executed")
}
    

In the example above, the deferred function checks for a panic and recovers from it, allowing the program to continue running safely.


go recover from panics go defer go panic error handling in Go