How to Use panic and recover in Go

Use panic to stop execution on critical errors and recover in a deferred function to catch and handle them gracefully.

Use panic to halt execution immediately when an unrecoverable error occurs, and wrap it with recover in a deferred function to catch the panic and resume normal flow.

func safeOperation() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    panic("something went wrong")
    fmt.Println("This line is never reached")
}