SoFunction
Updated on 2025-03-04

Detailed explanation of the role of panic and recover in GoLang

The problem leads to:

What are the functions of panic and recovery in Go language?

answer:

In Go,panicandrecoveris a mechanism for handling program errors and recovery.

panic:

  • panicis a built-in function that aborts the execution of the current function. When some errors or exceptions that cannot be executed within the function can be calledpanicto raise a runtime error.
  • CallpanicExecution of the current function will be stopped immediately and propagated up along the call stack until the program terminates. At the same time, a function call (defer) that is delayed in the function will be executed. If not processedpanic, the program will print out the call stack information and exit in a non-zero state.

Example:

func processFile(filename string) {
    if filename == "" {
        panic("Filename cannot be empty!")
    }
    // ... other code
}

recover:

  • recoveris a built-in function forpanicRecovery in the middle. It can only be called in a defer function.
  • When the program executespanicWhen , it aborts the execution of the current function and then executes the delay function of the function. Called in a delay functionrecoverCan be capturedpanic, prevent it from continuing to propagate upwards, thereby allowing the program to continue to execute.

Example:

func handlePanic() {
    if r := recover(); r != nil {
        ("Recovered from panic:", r)
        // You can perform additional recovery actions here
    }
}
func processFile(filename string) {
    defer handlePanic() // defer a function to recover from panic
    if filename == "" {
        panic("Filename cannot be empty!")
    }
    // ... other code
}

Use scenarios:

  • panicIt is usually used to indicate that the program encounters serious problems and cannot continue to execute, such as dereference of null pointers, array out of bounds, etc. In this case, we can usepanicto abort the program and log problems by outputting logs or other means.
  • recoverIt is usually used to try to avoid program crashes, do some cleaning work or logging when necessary, and try to keep the program running. But it should be used with cautionrecover, because abuse of it can lead to hard to debug code.

Example:
Suppose we have a function that reads the configuration file and triggers when an error is encountered during the reading processpanic, use it at the same timerecoverto recover and handle the error.

package main
import (
    "fmt"
    "encoding/json"
    "os"
)
type Config struct {
    Port    int
    Timeout int
    // Other configuration items...}
func readConfig(filename string) (*Config, error) {
    file, err := (filename)
    if err != nil {
        return nil, err
    }
    defer ()
    decoder := (file)
    var config Config
    if err := (&config); err != nil {
        panic(("Failed to decode config file: %v", err))
    }
    return &config, nil
}
func main() {
    defer func() {
        if r := recover(); r != nil {
            ("Recovered from panic:", r)
        }
    }()
    config, err := readConfig("")
    if err != nil {
        ("Error reading config file: %v\n", err)
        return
    }
    ("Config:", config)
}

summary:

panicandrecoverIt is a mechanism used in Go language for handling exceptions and errors that can help us deal with unexpected situations and make our programs more robust. But when writing code, you should carefully consider when to use itpanicandrecover, avoid abuse to ensure the maintainability and stability of the program.

This is the end of this article about the detailed explanation of the role of panic and recover in GoLang. For more related content on GoLang panic and recover, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!