Sobes.tech
Junior — Middle

How can you handle a program's emergency termination caused by a panic when using the defer statement?

sobes.tech AI

Answer from AI

In Go, to handle a program's emergency termination caused by a panic, the defer statement is often used together with the recover() function. In a deferred function (defer), you can call recover(), which intercepts the panic and allows the program to continue execution or terminate gracefully.

Example:

func safeFunction() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Panic caught:", r)
            // Cleanup or logging can be done here
        }
    }()

    // Code that might cause a panic
    panic("something went wrong")
}

Thus, defer guarantees the execution of the function, and recover() allows handling the panic without causing an abrupt program termination.