Go Q & A

 

How do you handle panics in Go?

In Go, a panic is a built-in mechanism for signaling that a program has encountered an unexpected error condition or unrecoverable state. When a panic occurs, the normal flow of execution is interrupted, and the program begins to unwind its stack, executing deferred function calls and releasing resources along the way.

 

To handle panics in Go, you can use the recover() function in combination with deferred function calls. The recover() function allows you to capture and handle panics gracefully within the scope of a deferred function. When a panic occurs, the recover() function returns the value that was passed to the panic() function, allowing you to inspect the panic value and take appropriate action.

 

Here’s an example of how to handle panics in Go using the recover() function:

go

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

func main() {
    defer recoverFromPanic()
    
    // Simulate a panic
    panic("Oops! Something went wrong.")
}

In this example, the recoverFromPanic() function is deferred using the defer keyword, ensuring that it is called when a panic occurs. Inside the recoverFromPanic() function, we use the recover() function to capture the panic value and print a message indicating that the program has recovered from a panic.

 

It’s important to note that the recover() function should only be used in conjunction with deferred function calls and should not be used to handle panics in general program logic. Panics should be reserved for exceptional circumstances where the program cannot safely continue execution.

Previously at
Flag Argentina
Mexico
time icon
GMT-6
Over 5 years of experience in Golang. Led the design and implementation of a distributed system and platform for building conversational chatbots.