ZetCode

Golang recover function

last modified May 8, 2025

This tutorial explains how to use the recover built-in function in Go. We'll cover panic recovery basics with practical examples of proper error handling.

The recover function is used to regain control of a panicking goroutine. It stops the panic sequence and returns the value passed to panic. Recover is only useful inside deferred functions.

In Go, recover works with panic and defer to handle exceptional situations. It allows graceful shutdown or continuation after unexpected errors.

Basic panic recovery example

The simplest use of recover catches a panic and prevents program crash. This example demonstrates basic panic recovery.
Note: Recover must be called within a deferred function.

basic_recover.go
package main

import "fmt"

func main() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
        }
    }()
    
    panic("something went wrong")
    
    fmt.Println("This line won't be executed")
}

The deferred function calls recover when the panic occurs. The program continues execution after the deferred function completes.

Recovering from division by zero

We can use recover to handle runtime errors like division by zero. This example shows practical error recovery in mathematical operations.

division_recover.go
package main

import "fmt"

func safeDivide(a, b int) (result int, err error) {
    defer func() {
        if r := recover(); r != nil {
            err = fmt.Errorf("division error: %v", r)
        }
    }()
    
    result = a / b
    return result, nil
}

func main() {
    res, err := safeDivide(10, 0)
    if err != nil {
        fmt.Println("Error:", err)
    } else {
        fmt.Println("Result:", res)
    }
}

The safeDivide function recovers from division by zero panic. It converts the panic into a regular error return value.

Recover in goroutines

Each goroutine needs its own panic recovery. This example shows how to properly handle panics in concurrent code.

goroutine_recover.go
package main

import (
    "fmt"
    "time"
)

func worker() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Worker recovered:", r)
        }
    }()
    
    fmt.Println("Worker started")
    time.Sleep(1 * time.Second)
    panic("worker panic")
    fmt.Println("Worker finished")
}

func main() {
    go worker()
    
    time.Sleep(2 * time.Second)
    fmt.Println("Main function completed")
}

The worker goroutine has its own recovery mechanism. The panic doesn't affect the main goroutine due to proper recovery.

Recover with error logging

We can combine recover with detailed error logging. This example demonstrates advanced panic recovery with stack traces.

logging_recover.go
package main

import (
    "fmt"
    "runtime/debug"
)

func riskyOperation() {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered from panic:", r)
            fmt.Println("Stack trace:")
            debug.PrintStack()
        }
    }()
    
    var nilMap map[string]string
    nilMap["key"] = "value" // Will panic
}

func main() {
    riskyOperation()
    fmt.Println("Program continues after recovery")
}

The recovery handler logs both the panic value and stack trace. This helps with debugging while allowing the program to continue.

Recover in web servers

Web servers should recover from panics to maintain availability. This example shows panic recovery in HTTP handlers.

http_recover.go
package main

import (
    "fmt"
    "net/http"
)

func panicHandler(w http.ResponseWriter, r *http.Request) {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Recovered in handler:", r)
            w.WriteHeader(http.StatusInternalServerError)
            fmt.Fprintf(w, "Internal server error")
        }
    }()
    
    panic("handler panic")
}

func main() {
    http.HandleFunc("/", panicHandler)
    fmt.Println("Server started on :8080")
    http.ListenAndServe(":8080", nil)
}

The HTTP handler recovers from panics and returns proper error responses. This prevents the entire server from crashing due to a single request.

Source

Go language specification

This tutorial covered the recover function in Go with practical examples of panic recovery in various scenarios.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Golang tutorials.