recover from a panic in go

In Go, a panic is a runtime error that occurs when a program cannot proceed due to an unexpected condition. When a panic occurs, Go runtime stops normal execution of the program and starts unwinding the stack, which means that it starts to go back through the function call stack and clear out any unrecovered resources until it reaches the main function.

However, we can recover from panic using recover() function. recover() function can only be called in a deferred function, and it returns the value passed to the call to panic(). If the defer function containing recover() is called within the scope of a panicked function, recover() stops the panic and returns the error value that caused the panic.

Here's an example of how to use recover() to handle a panic:

main.go
func performDivision(a, b int) (result int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("recovered from panic: %v", r)
        }
    }()
    
    // Check for division by zero
    if b == 0 {
        panic("division by zero")
    }
    
    result = a / b
    return result, nil
}

func main() {
    res, err := performDivision(10, 2)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Println(res)
}
467 chars
25 lines

In the example above, we define performDivision() function that can panic if the divisor is zero. We defer a function that contains the recover() call. When the panic occurs, the recover() function is called, and the error is caught and returned as an error instead. This allows us to handle the panic gracefully and return an error instead of letting the panic crash the program.

gistlibby LogSnag