skip to content
Alvin Lucillo

Go try-catch with defer and recover

/ 1 min read

💻 Tech

In Go, you can do something like a try-catch in some programming languages with the use of defer and recover. Here’s an example:

func div(a,b int) (int, error) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("recovered", r)
        }
    }()

    return a/b, nil
}

func main() {
    fmt.Println(div(1,0)) // recovered runtime error: integer divide by zero
}

recover gives the function a chance to perform tasks to handle a panic such as logging an error. In the example above, dividing by zero will cause a panic, but the deferred function will catch it and print the message “recovered”.