0
0
Goprogramming~5 mins

Recover usage in Go

Choose your learning style9 modes available
Introduction

Recover helps your program catch and handle errors so it doesn't crash suddenly.

When you want to stop your program from crashing after a mistake.
When you want to clean up or log information after an error happens.
When you want to keep your program running even if one part fails.
When you want to handle unexpected problems gracefully.
Syntax
Go
defer func() {
    if r := recover(); r != nil {
        // handle the error here
    }
}()

defer delays running the function until the surrounding function finishes.

recover() catches the error (panic) if there is one.

Examples
This example prints the error message when a panic happens.
Go
defer func() {
    if r := recover(); r != nil {
        fmt.Println("Recovered from panic:", r)
    }
}()
This function uses recover to avoid crashing when dividing by zero.
Go
func safeDivide(a, b int) int {
    defer func() {
        if r := recover(); r != nil {
            fmt.Println("Cannot divide by zero")
        }
    }()
    return a / b
}
Sample Program

This program starts, then panics with a message. The deferred function catches the panic and prints a recovery message. The last print does not run because of the panic.

Go
package main

import "fmt"

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

    fmt.Println("Start program")
    panic("Something went wrong!")
    fmt.Println("This will not run")
}
OutputSuccess
Important Notes

Recover only works inside a deferred function.

If you don't recover, a panic will stop your program immediately.

Use recover carefully to avoid hiding real problems.

Summary

Recover helps catch errors and keep your program running.

Use defer with recover to handle panics safely.

Recover must be called inside a deferred function.