Sobes.tech
Middle+

What is a panic in Go?

sobes.tech AI

Answer from AI

Panic in Go is a mechanism for handling critical errors, where the execution of the program is immediately interrupted. A panic is triggered by the panic() function, and it results in stopping the current goroutine and starting a stack unwinding process during which deferred functions (defer) are called.

Panic is used to signal unexpected errors that the program cannot or should not recover from on its own.

Example of using panic:

func divide(a, b int) int {
    if b == 0 {
        panic("division by zero")
    }
    return a / b
}

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

    fmt.Println(divide(10, 2)) // 5
    fmt.Println(divide(10, 0)) // will cause panic
    fmt.Println("This code will not execute")
}

Here, recover() allows catching the panic and continuing the program execution. Panic is a more severe way of error handling compared to error return values.

What is a panic in Go? — Golang - sobes.tech